# Send an email from a view

> Configure SMTP in the config file, render a view as the message body with MAIL(), and send plain HTML with HTMLMAIL().

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 82d673e47df8e2c89407aa68da87b54706364712401f9ee8742dd3918b58e706
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

Total.js sends mail over SMTP. The server and the sender go in the `config` file: `mail_smtp` is the server, `mail_smtp_options` an object with the rest of the connection settings (`port`, `user`, `password`, `secure`...) and `mail_from` / `mail_from_name` the sender. `mail_reply`, `mail_cc` and `mail_bcc` add the same headers to every message.

`MAIL(email, subject, view, model, [language], [callback])` renders `views/<view>.html` with the model (the same views as for pages, including `@(...)` localization) and sends the result as the HTML body. `email` can be one address or several separated by commas. `HTMLMAIL(email, subject, html, [language], [callback])` sends a string you built yourself. Both return the message; `callback(err)` runs when the server has accepted or rejected it, and `err` is `null` on success.

Messages are queued and sent right after the current tick, so `MAIL()` never blocks the request. Wait for the callback only when the user has to know whether it worked.

```text config
name : Mail example
mail_smtp : 127.0.0.1
mail_smtp_options : { port: 2526 }
mail_from : hello@example.com
mail_from_name : Example
```

The view is rendered **with the layout**, like any page, so `views/layout.html` must exist (the app crashes the request with an `ENOENT` error otherwise). A mail layout can be as small as the one below, or you can use your page layout.

```html views/layout.html
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" /></head>
<body style="font-family:Arial">@{body}</body>
</html>
```

```html views/welcome.html
<h1>Welcome, @{model.name}!</h1>
<p>Your account is ready.</p>
```

```js controllers/mail.js
exports.install = function() {
	ROUTE('POST /welcome/ @json', welcome);
	ROUTE('POST /note/ @json', note);
};

function welcome($) {
	MAIL($.body.email, 'Welcome aboard', 'welcome', { name: $.body.name }, function(err) {
		$.json({ sent: !err, error: err ? err.toString() : null });
	});
}

function note($) {
	HTMLMAIL($.body.email, 'A short note', '<p>Plain <b>HTML</b> message</p>', function(err) {
		$.json({ sent: !err, error: err ? err.toString() : null });
	});
}
```
