Spanish Total.js
English
Documentation For AI agents
Contents

Sending email

MAIL(), HTMLMAIL(), LOGMAIL(), the Mail module, the message object and the SMTP keys.

.md GitHub
On this page

This page lists the global mail functions, the Mail module with its events, the methods and properties of the message object, and the config keys for SMTP and the default sender. The guide Sending email explains how they work together, with examples.

API

method

MAIL()

Renders a view and sends it as an e-mail.
ParameterTypeDescription
email String|Array One address, comma-separated addresses, or an array of addresses. Each becomes a To: recipient.
subject String The subject.
view String The name of the view, e.g. mail/welcome.
model? Object The model of the view.
language? String The language for the view and the subject.
callback? Function function(err, message), the same as message.callback().

Returns Message The message that will be sent.

Renders the view view (a path in /views/ without .html) with model and sends the HTML to email. The sender, the reply address and the copies come from mail_from, mail_from_name, mail_reply, mail_cc and mail_bcc (or from/name of CONF.smtp). With language, the view is rendered in that language and a subject with @(...) is translated. The message is sent on the next turn of the event loop, so you can still change the returned message. When language is a function, it is used as the callback.

Welcome e-mail
MAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language, function(err) {
	err && console.log('Not sent', err);
});
method

HTMLMAIL()

Sends an e-mail with an HTML body.
ParameterTypeDescription
email String|Array One address, comma-separated addresses, or an array of addresses. Each becomes a To: recipient.
subject String The subject.
body String The HTML.
language? String The language for translating the subject and the body.
callback? Function function(err, message), the same as message.callback().

Returns Message The message that will be sent.

Sends body as HTML. A body without a <body> tag is wrapped in a simple HTML document with the subject as the title. With language, @(...) texts in the subject and the body are translated. The defaults are the same as for MAIL(). When language is a function, it is used as the callback.

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

LOGMAIL()

Sends a short report as preformatted text.
ParameterTypeDescription
email String|Array One address, comma-separated addresses, or an array of addresses. Each becomes a To: recipient.
subject? String The subject (default CONF.name).
body String|Object The text, or an object to serialize.
callback? Function function(err, message), the same as message.callback().

Returns Message The message that will be sent.

Wraps body in a <pre> block and sends it. A string is inserted as it is, so it can contain HTML. An object is serialized to JSON and HTML-encoded. Without subject (two arguments, or a function as the third one), CONF.name is the subject. The defaults are the same as for MAIL().

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

DEF.onMail

The function that builds and sends the messages of MAIL(), HTMLMAIL() and LOGMAIL().
ParameterTypeDescription
email String|Array One address, comma-separated addresses, or an array of addresses. Each becomes a To: recipient.
subject String The subject.
body String The HTML body.
callback? Function The callback.
reply? String A reply address instead of mail_reply.

Returns Message The message.

Called as DEF.onMail(email, subject, body, callback, reply). It creates the message, adds the recipients, the sender (mail_from or CONF.smtp.from/user, mail_from_name or CONF.smtp.name), the reply address (reply or mail_reply), mail_cc and mail_bcc, sets the callback and schedules the sending. It must return the message. When callback is a string, it is taken as reply.

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;
};
class

Mail

The global SMTP client.

Returns Object

Mail is the mailer of the framework. It creates messages (Mail.create()), sends them (Mail.send(), Mail.send2()), tests a server (Mail.try()) and emits the send and error events. Mail.Message (also Mail.Mail) is the constructor of messages.

Create and send
var msg = Mail.create('Hello', '<p>Hello</p>');
msg.from('info@example.com').to('user@example.com').send2();
method

Mail.create()

Creates a new message.
ParameterTypeDescription
subject String The subject.
body String The body (HTML by default).

Returns Message A new message.

Returns a new message with the subject and the body. Unlike MAIL(), nothing is set or sent for you: add the sender and the recipients and call message.send2() or message.send().

Create
var msg = Mail.create('Hello', '<p>Hello from Total.js</p>');
msg.from('info@example.com', 'My application');
msg.to('user@example.com');
msg.send2();
method

Mail.send()

Sends one or more messages with the given SMTP options.
ParameterTypeDescription
options Object The SMTP options.
messages Message|Array A message or an array of messages.
callback? Function function(err).

Opens a connection with options (the same keys as CONF.smtp), sends the messages one after another and closes the connection. The callback receives err when the connection or the login fails. Use message.callback() for the result of each message.

Two messages, one connection
var a = Mail.create('A', '<p>A</p>').from('info@example.com').to('a@example.com');
var b = Mail.create('B', '<p>B</p>').from('info@example.com').to('b@example.com');
Mail.send(CONF.smtp, [a, b]);
method

Mail.send2()

Sends messages with CONF.smtp.
ParameterTypeDescription
messages Message|Array A message or an array of messages.
callback? Function function(err).

The same as Mail.send(CONF.smtp, messages, callback).

Send
Mail.send2([msg1, msg2]);
method

Mail.try()

Tests the connection and the login to an SMTP server.
ParameterTypeDescription
options Object The SMTP options.
callback? Function function(err).

Returns Promise Without a callback.

Connects with options, logs in and quits without sending anything. Without a callback it returns a promise.

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

Mail.debug

Prints the SMTP conversation to the console.

Returns Boolean Default false.

With true, every line sent to and received from the server is printed. Default false.

Debug
Mail.debug = true;
event

Mail.on('send')

Emitted when a connection is ready to send.
ParameterTypeDescription
connection Object The internal connection object.

Mail.on('send', function(connection) {}). Emitted when the client starts the SMTP conversation of a connection.

Listen
Mail.on('send', function() {
	console.log('SMTP connection ready');
});
event

Mail.on('error')

Emitted on SMTP errors.
ParameterTypeDescription
err Error|String The error.
connection Object The internal connection object.

Mail.on('error', function(err, connection) {}). Emitted when the connection fails, the login is refused or the server answers with an error. err is an Error or the reply line of the server.

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

ON('$mail')

Emitted for every message that is being sent.
ParameterTypeDescription
message Message The message.

ON('$mail', function(message) {}). Emitted just before the message is written to the SMTP server.

Log every e-mail
ON('$mail', function(message) {
	console.log('Sending', message.subject, 'to', message.email_to);
});
class

Mail.Message

The message object.

Returns Object

A message is returned by MAIL(), HTMLMAIL(), LOGMAIL() and Mail.create(); new Mail.Message(subject, body) creates one too (Mail.Mail is an alias). Its methods return the message, so calls can be chained. The recipients are in email_to, email_cc, email_bcc and email_reply (arrays), the sender in email_from and email_from_name.

Chain
Mail.create('Hi', '<p>Hi</p>').from('info@example.com').to('a@example.com').cc('b@example.com').send2();
method

message.to()

Adds a recipient.
ParameterTypeDescription
email String One address.
clear? Boolean Remove the current recipients first. Default: false

Returns Message The message, for chaining.

Adds one address to the To: header. With clear, the current recipients are removed first.

Recipients
msg.to('a@example.com').to('b@example.com');
method

message.cc()

Adds a copy recipient.
ParameterTypeDescription
email String One address.
clear? Boolean Remove the current copies first. Default: false

Returns Message The message, for chaining.

Adds one address to the Cc: header. With clear, the current copies are removed first.

Copy
msg.cc('boss@example.com');
method

message.bcc()

Adds a blind copy recipient.
ParameterTypeDescription
email String One address.
clear? Boolean Remove the current blind copies first. Default: false

Returns Message The message, for chaining.

Adds one address that receives the message without being listed in the headers. With clear, the current blind copies are removed first.

Blind copy
msg.bcc('archive@example.com');
method

message.reply()

Adds a reply address.
ParameterTypeDescription
email String One address.
clear? Boolean Remove the current reply addresses first. Default: false

Returns Message The message, for chaining.

Adds one address to the Reply-To: header. With clear, the current reply addresses are removed first.

Reply to support
msg.reply('support@example.com');
method

message.from()

Sets the sender.
ParameterTypeDescription
email String The address.
name? String The display name.

Returns Message The message, for chaining.

Sets the From: address and, optionally, the display name. message.sender() is the same method.

Sender
msg.from('info@example.com', 'My application');
method

message.sender()

An alias of message.from().
ParameterTypeDescription
email String The address.
name? String The display name.

Returns Message The message, for chaining.

The same as message.from(email, [name]).

Sender
msg.sender('info@example.com');
method

message.attachment()

Attaches a file from the disk or a Buffer.
ParameterTypeDescription
filename String|Buffer The path to the file, or a Buffer with the content.
name String The file name for the recipient, with its extension.
contentid? String The content ID for an inline file.

Returns Message The message, for chaining.

Adds the file filename, or the content of a Buffer, as an attachment. name is the file name shown to the recipient, and its extension sets the content type (application/octet-stream for unknown ones). With contentid, the file is an inline part that the HTML body refers to as cid:<contentid>. The file is read when the message is sent.

Attach a PDF
msg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');
Inline image
var msg = HTMLMAIL('user@example.com', 'News', '<img src="cid:logo" />');
msg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');
From a Buffer
var pdf = Buffer.from('%PDF-1.4 ...');
var msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');
msg.attachment(pdf, 'invoice.pdf');
method

message.attachmentfs(storage, id, [name], [contentid])

Attaches a file from a file storage.
ParameterTypeDescription
storage String The name of the file storage.
id String The id of the file in the storage.
name? String The file name for the recipient, with its extension. Default: the name stored with the file.
contentid? String The content ID for an inline file.

Returns Message The message, for chaining.

Adds a file of a file storage as an attachment: storage is the name of the storage (as in FILESTORAGE(name)) and id the id of the file. Without name, the recipient sees the name of the file in the storage and the content type is the type stored with the file; with name, its extension sets the content type. With contentid, the file is an inline part that the HTML body refers to as cid:<contentid>.

The file is read when the message is sent. When it does not exist, the error is written to the error log and the message is sent without the attachment.

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

var msg = HTMLMAIL('user@example.com', 'Contract', '<p>The contract is attached.</p>');
msg.attachmentfs('documents', id);
Another name
msg.attachmentfs('documents', id, 'contract-2025.pdf');
method

message.unsubscribe()

Adds the List-Unsubscribe headers.
ParameterTypeDescription
url String The unsubscribe URL or e-mail address.

Returns Message The message, for chaining.

Adds List-Unsubscribe and List-Unsubscribe-Post: List-Unsubscribe=One-Click. A value that starts with http: or https: is used as a URL; any other value is an e-mail address (mailto:).

Newsletter
msg.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);
method

message.callback()

Sets the function called with the result of the message.
ParameterTypeDescription
fn Function function(err, message).

Returns Message The message, for chaining.

fn(err, message) is called with an empty err when the message has been handed over to the server, or with an error: the reply line of the server (in upper case) when it refuses the message or the login, No SMTP server configuration., or a connection error or timeout. An error that reaches a callback is not written to the error log. MAIL(), HTMLMAIL() and LOGMAIL() set it from their callback argument.

Result
msg.callback(function(err, message) {
	if (err)
		console.log('Not sent:', message.subject, err);
});
method

message.manually()

Stops the automatic sending.

Returns Message The message, for chaining.

MAIL(), HTMLMAIL() and LOGMAIL() send the message on the next turn of the event loop. Call manually() right after them to cancel that, and send the message later with message.send2() or message.send().

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

message.send2()

Sends the message with CONF.smtp.
ParameterTypeDescription
callback? Function function(err).

Sends the message with the configured SMTP server (CONF.smtp).

Send
Mail.create('Hello', '<p>Hello</p>').from('info@example.com').to('user@example.com').send2(function(err) {
	err && console.log(err);
});
method

message.send(options)

Sends the message with other SMTP options.
ParameterTypeDescription
options Object The SMTP options.

Returns Message The message, for chaining.

Sends the message over a new connection with options (the same keys as CONF.smtp). Use message.callback() for the result.

Another server
msg.callback(function(err) {
	err && console.log(err);
});
msg.send({ server: 'smtp.other.com', port: 587, user: 'me@other.com', password: 'secret' });
property

message.subject

The subject.

Returns String

The subject of the message. Non-ASCII characters are encoded for you.

Change
msg.subject = 'Updated subject';
property

message.body

The body.

Returns String

The body of the message: HTML, or plain text when type is plain.

Change
msg.body = '<p>New text</p>';
property

message.type

The type of the body.

Returns String Default html.

html (default) or plain. It becomes the Content-Type of the body (text/html or text/plain).

Plain text
var msg = Mail.create('Hello', 'Hello in plain text');
msg.type = 'plain';
property

message.headers

Extra headers of the message.

Returns Object

An object of header names and values written into the message as they are. It is not set by default.

Custom header
msg.headers = { 'X-Campaign': 'spring-2025' };
method

message.high()

Marks the message as high priority.

Returns Message The same message.

Adds the header X-Priority: 1. Returns the message.

Urgent
HTMLMAIL('admin@example.com', 'Disk full', '<p>The disk is full.</p>').high();
method

message.low()

Marks the message as low priority.

Returns Message The same message.

Adds the header X-Priority: 5. Returns the message.

Weekly digest
MAIL(user.email, 'Your week', 'mail/digest', model).low();
method

message.confidential()

Marks the message as confidential.

Returns Message The same message.

Adds the header Sensitivity: Company-Confidential. Returns the message.

Confidential report
HTMLMAIL('board@example.com', 'Salaries', html).confidential().high();
config

CONF.smtp

The SMTP server and its options.

Returns Object

An object with server (or host, hostname, smtp, url), port, secure, user, password, token, tls, timeout, from and name. With secure: true the connection uses TLS from the start and port defaults to 465; otherwise set port. The key mail in the config file is the same.

Before the connection, server is converted with U.tohost(): an international name is sent as punycode and an IPv4 address in its dotted form (127.1 becomes 127.0.0.1). A value that is not a valid host name gives the error Invalid SMTP server hostname. and nothing is sent.

/config
smtp (json) : {"server":"smtp.example.com","port":465,"secure":true,"user":"info@example.com","password":"secret"}
STARTTLS on port 587
smtp (json) : {"server":"smtp.example.com","port":587,"user":"info@example.com","password":"secret"}
config

CONF.mail_smtp

The SMTP server name.

Returns String

Sets CONF.smtp.server. Use it with mail_smtp_options instead of one smtp object.

/config
mail_smtp : smtp.example.com
config

CONF.mail_smtp_options

The SMTP options without the server.

Returns Object

An object whose keys are copied into CONF.smtp (port, secure, user, password...).

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

CONF.mail_from

The default sender address.

Returns String

The From: address of MAIL(), HTMLMAIL() and LOGMAIL(). Without it, CONF.smtp.from or CONF.smtp.user is used.

/config
mail_from : info@example.com
config

CONF.mail_from_name

The default sender name.

Returns String

The display name of the sender of MAIL(), HTMLMAIL() and LOGMAIL(). Without it, CONF.smtp.name is used.

/config
mail_from_name : My application
config

CONF.mail_reply

The default reply address.

Returns String

One address added as Reply-To: to the messages of MAIL(), HTMLMAIL() and LOGMAIL().

/config
mail_reply : support@example.com
config

CONF.mail_cc

A default copy recipient.

Returns String

One address added as Cc: to the messages of MAIL(), HTMLMAIL() and LOGMAIL().

/config
mail_cc : office@example.com
config

CONF.mail_bcc

A default blind copy recipient.

Returns String

One address added as a blind copy to the messages of MAIL(), HTMLMAIL() and LOGMAIL().

/config
mail_bcc : archive@example.com
config

$tapimail : true

Sends the messages through the Total.js API instead of SMTP.

Returns Boolean

Default false. With true, MAIL(), HTMLMAIL(), LOGMAIL() and message.send2() send the message with API('TAPI', 'mail', data) and the token secret_totalapi; $tapi must be true (the default). The service gets the recipients (to, cc, bcc, reply), from, subject, type, body, priority, unsubscribe and confidential. Attachments and message.headers are not sent. The callback of the message gets the answer of the service.

/config
$tapimail       : true
secret_totalapi : your-totalapi-token
Made in Europe