Spanish Total.js
English
Documentation For AI agents
Contents

Sending email

Send e-mail with MAIL(), HTMLMAIL() and LOGMAIL(), configure SMTP, add attachments and build messages with the Mail module.

.md GitHub
On this page

Total.js 5 sends e-mail over SMTP with its own client, the Mail module. Three global functions cover most needs: MAIL() renders a view as the body, HTMLMAIL() sends HTML you already have, and LOGMAIL() sends a quick text report. Each one returns a message object that you can still change before it leaves.

MAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' });
HTMLMAIL('user@example.com', 'Your order', '<p>Thank you for your order.</p>');
LOGMAIL('admin@example.com', 'Import finished', { count: 120 });

The full list of functions, methods and keys is in the reference of Sending email.

Configuration

The SMTP server is set in the config file with the smtp key (mail is an alias). The value is an object; the framework stores it as CONF.smtp.

smtp (json)     : {"server":"smtp.example.com","port":465,"secure":true ,"user":"info@example.com","password":"secret"}
mail_from       : info@example.com
mail_from_name  : My application
OptionMeaning
serverThe host name or IP address of the SMTP server (host, hostname, smtp and url are read when server is missing). An international name is converted to punycode and an IPv4 address to its dotted form
portThe port. With secure: true it defaults to 465; otherwise set it (usually 25 or 587)
securetrue opens a TLS connection from the start (implicit TLS)
user, passwordThe login. The client uses AUTH LOGIN, or AUTH PLAIN when the server also offers XOAUTH and no token is set
tokenAn OAuth2 access token, used with user when the server offers XOAUTH2
tlsExtra Node.js TLS options used for the STARTTLS upgrade
timeoutThe connection timeout in milliseconds (default 60000)
from, nameThe sender address and name used when mail_from and mail_from_name are not set

On a plain connection (for example port 587) the client upgrades to TLS with STARTTLS before it logs in when the server asks for TLS or offers the login only after it. To be sure that the login is always encrypted, use secure: true with port 465.

Instead of one object you can also set the server and the options separately:

mail_smtp          : smtp.example.com
mail_smtp_options  : {"port":587,"user":"info@example.com","password":"secret"}

The keys mail_from, mail_from_name, mail_reply, mail_cc and mail_bcc are the defaults that MAIL(), HTMLMAIL() and LOGMAIL() put into every message. mail_reply, mail_cc and mail_bcc hold one address each. See Configuration for the format of the file.

MAIL() with a view

MAIL(email, subject, view, [model], [language], [callback]) renders a view from /views/ and sends the result. The model is available in the view as model, exactly as in Views. Start a mail view with @{layout('')}: without it the view is rendered into /views/layout.html, and MAIL() fails if that file does not exist.

MAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' }, function(err) {
    if (err)
        console.log('Not sent:', err);
});
<!-- views/mail/welcome.html -->
@{layout('')}
<h1>Hello @{model.name}</h1>
<p>Your account is ready.</p>

With language, the view is rendered in that language and a subject that contains @(...) is translated as well. See Localization.

MAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language);

The email argument is one address, a comma-separated string of addresses, or an array. Each address becomes a To: recipient.

HTMLMAIL() and LOGMAIL()

HTMLMAIL(email, subject, body, [language], [callback]) sends HTML from a string. When the body has no body tag, it is wrapped in a simple HTML document with the subject as the title.

HTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');

LOGMAIL(email, [subject], body, [callback]) is meant for reports to yourself. The body is shown as preformatted text: a string as it is (it can contain HTML), an object serialized to JSON and HTML-encoded. Without a subject, CONF.name is used.

LOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });
LOGMAIL('admin@example.com', 'The backup has finished.');

Changing the message before it is sent

All three functions return the message and send it a moment later (on the next turn of the event loop). Until then you can add recipients, attachments or headers:

var msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');
msg.cc('accounting@example.com');
msg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');
msg.unsubscribe('https://example.com/unsubscribe/?id=123');

message.manually() stops the automatic sending. You send the message yourself later with message.send2():

var msg = MAIL('user@example.com', 'Report', 'mail/report', data);
msg.manually();

// ... later
msg.send2(function(err) {
    console.log(err ? 'Failed' : 'Sent');
});

Attachments

message.attachment(filename, name, [contentid]) attaches a file from the disk. name is the file name the recipient sees, and its extension sets the content type. With a contentid the file is an inline part that the HTML refers to as cid:contentid:

var msg = HTMLMAIL('user@example.com', 'Newsletter', '<img src="cid:logo" /><p>News of the month</p>');
msg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');

The first argument can also be a Buffer, for a file you create in memory. message.attachmentfs(storage, id, [name], [contentid]) attaches a file of a file storage; without name, the name and the type stored with the file are used:

var id = UID();
await FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));

var msg = HTMLMAIL('user@example.com', 'Your documents', '<p>The files are attached.</p>');
msg.attachment(Buffer.from('id;name\n1;Peter\n'), 'users.csv');
msg.attachmentfs('documents', id);

Building a message yourself

Mail.create(subject, body) returns a new message that nobody sends for you. Set the sender and the recipients, then send it with the configured server (message.send2()) or with other SMTP options (message.send(options)).

var msg = Mail.create('Hello', '<p>Hello from Total.js</p>');
msg.from('info@example.com', 'My application');
msg.to('user@example.com');
msg.reply('support@example.com');
msg.callback(function(err) {
    err && console.log(err);
});
msg.send2();

The body is HTML by default. Set msg.type = 'plain' for a plain-text body. msg.headers is an object of extra headers.

msg.high() and msg.low() set the priority of the message (the header X-Priority: 1 or X-Priority: 5), and msg.confidential() adds Sensitivity: Company-Confidential. The three methods return the message, so you can chain them:

HTMLMAIL('boss@example.com', 'Server is down', '<p>The server does not answer.</p>').high().confidential();

Mail.send(options, messages, [callback]) sends one message or an array of messages over a single connection. Mail.try(options) only connects and logs in, which is useful to check SMTP settings:

Mail.try(CONF.smtp).then(function() {
    console.log('SMTP works');
}).catch(function(err) {
    console.log('SMTP error:', err);
});

Errors and events

The callback of MAIL(), HTMLMAIL() and LOGMAIL() (the same as message.callback()) is called as callback(err, message). err is empty when the message has been handed over to the server. Otherwise it describes the problem:

  • the server refuses the message (for example an unknown recipient): the reply line of the server,
  • CONF.smtp is set but has no server: No SMTP server configuration. Without an smtp key CONF.smtp is undefined and the functions throw a TypeError,
  • the server is not a valid host name: Invalid SMTP server hostname.,
  • the connection fails or times out.

A refused login also gives the reply line of the server. Reply lines are in upper case.

An error that reaches a callback is not written to the error log; without a callback, it is logged with F.error().

Mail is an event emitter, and the framework emits a global event for every message:

ON('$mail', function(message) {
    console.log('Sending', message.subject, 'to', message.email_to);
});

Mail.on('error', function(err) {
    console.log('SMTP error', err);
});

Mail.debug = true prints the whole SMTP conversation to the console.

Sending through the Total.js API

With $tapimail : true the messages do not go to your SMTP server. They are sent by the Total.js API service (see APIs) with the token secret_totalapi, so you need no SMTP settings:

$tapimail       : true
secret_totalapi : your-totalapi-token

MAIL(), HTMLMAIL(), LOGMAIL() and message.send2() use it. The service gets the recipients, the sender, the subject, the body, the type, the priority, the unsubscribe link and the confidential flag; attachments and msg.headers are not sent. The callback of the message runs with the answer of the service. $tapi must stay true (the default).

Customizing

DEF.onMail is the function behind the three globals. Replace it to change how messages are built, for example to add a header to every message:

var onmail = DEF.onMail;
DEF.onMail = function(email, subject, body, callback, reply) {
    var msg = onmail(email, subject, body, callback, reply);
    msg.headers = { 'X-Application': CONF.name };
    return msg;
};

New methods for all messages can be added with F.extend('mail', name, fn); see Prototypes.

Made in Europe