ForgeTotal.js 5
en

Total.js 5

Send an email from a view

Total.js 5 · total5@0.0.19 mailsmtpemail Executed against Total.js 5

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.

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.

views/layout.html
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" /></head>
<body style="font-family:Arial">@{body}</body>
</html>
views/welcome.html
<h1>Welcome, @{model.name}!</h1>
<p>Your account is ready.</p>
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 });
	});
}