Spanish Total.js
English
Documentation For AI agents
Contents

Mail

Global mail functions, the mail configuration, the Mail module and the message object.

.md GitHub
On this page

MAIL(), HTMLMAIL(), LOGMAIL() and controller.mail() send email with the SMTP server from the configuration; the Mail module creates and sends messages to any server. In this reference message is a message returned by these functions or by Mail.create(). The guide Sending email explains how to use them with examples; this page is the exact reference.

API

method

MAIL(address, subject, view, [model], [language], [callback])

Renders a view and sends it as an HTML email.
ParameterTypeDescription
address String|Array One email address or an array of addresses; each one becomes a To recipient.
subject String The subject.
view String The name of a view in views/, for example mails/welcome.
model? Object The model of the view.
language? String A language for the subject and the view.
callback? Function Called with function(err, message) when the message has been written to the server, or with the reply line when the server rejects it.

Returns MailMessage The message, before it is sent.

The view is rendered without a layout; the model is available as model. With language, the subject is translated (a subject with @(...) is translated by its parts) and the view is rendered in this language. A view name that starts with =theme/ is taken from this theme. The sender, reply-to and copies come from the configuration. The message is sent on the next tick, so you can still change it. callback can also be the fifth argument and language the sixth.

A welcome email
MAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {
	err && console.log('Not sent', err);
});
Translated, with an attachment
MAIL(user.email, '@(Your invoice)', 'mails/invoice', invoice, user.language).attachment(filename, 'invoice.pdf');
method

HTMLMAIL(address, subject, body, [language], [callback])

Sends an HTML string as an email.
ParameterTypeDescription
address String|Array One email address or an array of addresses; each one becomes a To recipient.
subject String The subject.
body String The HTML of the message.
language? String A language for the subject and the body.
callback? Function Called with function(err, message) when the message has been written to the server, or with the reply line when the server rejects it.

Returns MailMessage The message, before it is sent.

A body without a <body> element is wrapped in a full HTML document with the subject as the title and a <body> with normalized CSS (no margin, Arial 14px). With language, the subject is translated and the @(...) texts of the body are translated too. callback can also be the fourth argument.

A short message
HTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');
method

LOGMAIL(address, [subject], body, [callback])

Sends a log or notification email.
ParameterTypeDescription
address String|Array One email address or an array of addresses; each one becomes a To recipient.
subject? String The subject. Default: name and version
body String|Object The text or an object to serialize.
callback? Function Called with function(err, message) when the message has been written to the server, or with the reply line when the server rejects it.

Returns MailMessage The message, before it is sent.

The body is placed in a <pre> element; an object is serialized as JSON. Without a subject, the subject is the name and the version of the configuration, for example My app v1.0.0.

Notify the administrator
LOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });
Only a body
LOGMAIL('admin@example.com', 'The import has finished.');
method

controller.mail(address, subject, view, [model], [callback])

Renders a view and sends it as an email from an action.
ParameterTypeDescription
address String|Array One email address or an array of addresses; each one becomes a To recipient.
subject String The subject; @(...) parts are translated.
view String The name of a view in views/.
model? Object The model of the view.
callback? Function Called with function(err, message) when the message has been written to the server, or with the reply line when the server rejects it.

Returns MailMessage The message, before it is sent.

It works like MAIL(); the subject is translated with the language of the controller (this.language), and the view is rendered with it. The layout of the controller is not used for the email.

After an order
exports.install = function() {
	ROUTE('POST /api/orders/', order);
};

function order() {
	var self = this;
	self.mail(self.body.email, '@(Your order)', 'mails/order', self.body);
	self.success();
}
delegate

DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}

Creates and schedules every message of MAIL(), HTMLMAIL(), LOGMAIL() and controller.mail().
ParameterTypeDescription
address String|Array One email address or an array of addresses; each one becomes a To recipient.
subject String The subject.
body String The HTML body.
callback? Function The message callback.
replyTo? String A reply-to address instead of mail_reply.

Returns MailMessage The message.

The default delegate creates a message with Mail.create(), adds the recipients, sets the sender from mail_from and name, adds replyTo or mail_reply, mail_bcc and mail_cc, and sends it on the next tick with message.send2(). Replace it to send email in another way; it must return a message object, because the callers change it (for example with manually()).

Add a header to the subject
var onmail = DEF.onMail;

DEF.onMail = function(address, subject, body, callback, replyTo) {
	return onmail(address, '[My app] ' + subject, body, callback, replyTo);
};
event

ON('mail', function(message) {})

Emitted for every message just before it is written to the SMTP server.
ParameterTypeDescription
message MailMessage The message being sent.

It is emitted for messages sent with the configuration and with Mail.send().

Audit outgoing email
ON('mail', function(message) {
	console.log('Mail to', message.address_to, message.subject);
});
command

CMD('clear_smtpcache')

Makes the next message read mail_smtp_options again.

The options of the SMTP connection are cached after the first message. Run this command after you change CONF.mail_smtp_options in code. LOADCONFIG() and Mail.use() clear the cache themselves.

Change the SMTP account
CONF.mail_smtp = 'smtp.example.com';
CONF.mail_smtp_options = { port: 465, secure: true, user: 'info@example.com', password: 'secret' };
CMD('clear_smtpcache');
config

mail_smtp : smtp.example.com

The host name of the SMTP server.

Used by MAIL(), HTMLMAIL(), LOGMAIL(), controller.mail(), message.send2() and Mail.send2(). When it is empty, the framework uses smtp. plus the domain of the sender address and stores it here.

In the config file
mail_smtp : smtp.example.com
config

mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }

The options of the SMTP connection.

In the config file it is a JavaScript object written as text; in code it is an object. Options:

  • port (default 25, or 465 with secure);
  • secure (default false): TLS from the start; the options are also passed to the TLS connection;
  • user and password: the login (AUTH LOGIN or AUTH PLAIN, as the server offers);
  • token: an OAuth 2.0 access token for AUTH XOAUTH2, used with user;
  • tls: options of the TLS connection; the client upgrades the connection with STARTTLS;
  • timeout (default 10000): the socket timeout in milliseconds.

With user and password, a server that announces ESMTP gets STARTTLS before the login.

SMTPS
mail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }
Submission port with STARTTLS
mail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }
OAuth 2.0
mail_smtp_options : { port: 587, user: 'info@example.com', token: 'ya29...' }
config

mail_smtp_keepalive : 10 minutes

How long a connection to the SMTP server stays open for the next messages.

Default 10 minutes. It is used by message.send2() while the application runs a web server; the open connection is reused for all messages to the same host. A number is in minutes. false opens a new connection for every message.

Close after each message
mail_smtp_keepalive : false
config

mail_from : info@example.com

The sender address of messages sent with the configuration.

The sender name is the name key of the configuration. mail_address_from is an older name of this key.

Sender
name      : My app
mail_from : info@example.com
config

mail_reply : support@example.com

A Reply-To address added to every message sent with the configuration.

Not used when the caller of DEF.onMail passes its own replyTo. mail_address_reply is an older name of this key.

Reply to support
mail_reply : support@example.com
config

mail_cc : office@example.com

A Cc address added to every message sent with the configuration.
Copy
mail_cc : office@example.com
config

mail_bcc : archive@example.com

A Bcc address added to every message sent with the configuration.

mail_address_copy is an older name of this key.

Archive every message
mail_bcc : archive@example.com
class

Mail

The global mail module: creates messages and sends them over SMTP.

Mail is available everywhere. It sends messages to any server (Mail.send()), with the configuration (Mail.send2()), checks a server (Mail.try(), Mail.use()) and emits the events send and error.

A message to any server
var message = Mail.create('Hello', '<p>Hello.</p>');
message.from('info@example.com');
message.to('peter@example.com');
Mail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], NOOP);
method

Mail.create(subject, body)

Creates an empty message.
ParameterTypeDescription
subject String The subject.
body String The body, HTML by default.

Returns MailMessage A new message.

The message has no sender and no recipients, and its type is html. It is not sent until you call message.send(), message.send2(), Mail.send() or Mail.send2().

Create and send
var message = Mail.create('Report', '<p>See the attachment.</p>');
message.from('info@example.com', 'My app');
message.to('peter@example.com');
message.attachment(PATH.root('report.pdf'));
message.send2();
method

Mail.send(smtp, [options], messages, [callback], [cache])

Sends one message or an array of messages over one connection.
ParameterTypeDescription
smtp String The host name of the SMTP server.
options? Object The connection options, the same as mail_smtp_options. Default: {}
messages MailMessage|Array A message or an array of messages.
callback? Function function(err), called once: when the first message has been written, or when the connection fails.
cache? Boolean|Number|String Keeps the connection open: true for 10 minutes, a number of minutes, or a text such as 5 minutes. Default: false

Returns Mail The mail module; nothing when the messages join an open connection.

All messages go through one connection in their order. options can be skipped when messages is an array. With cache, the connection stays open and later calls for the same host add their messages to it; such a later call does not call its callback, so use message.callback() there.

Two messages
Mail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [a, b], function(err) {
	err && console.log(err);
});
method

Mail.send2(messages, [callback])

Sends messages with mail_smtp and mail_smtp_options.
ParameterTypeDescription
messages MailMessage|Array A message or an array of messages.
callback? Function function(err), called once: when the first message has been written, or when the connection fails. Use message.callback() for each message.

Returns Mail The mail module.

The same as Mail.send() with the server and the options of the configuration.

A newsletter
var messages = users.map(function(user) {
	var message = Mail.create('News', html);
	message.from(CONF.mail_from, CONF.name);
	message.to(user.email);
	return message;
});

Mail.send2(messages, function(err) {
	err && console.log(err);
});
method

Mail.try(smtp, [options], [callback])

Checks an SMTP server: connects, signs in and quits.
ParameterTypeDescription
smtp String The host name of the SMTP server.
options? Object The connection options, the same as mail_smtp_options. Default: {}
callback? Function function(err).

Returns Mail|Promise The mail module, or a promise without a callback.

No message is sent. Without a callback it returns a promise that is rejected with the error.

With a callback
Mail.try('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {
	console.log(err ? 'Failed' : 'Works');
});
With a promise
try {
	await Mail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' });
} catch (err) {
	console.log('SMTP failed', err);
}
method

Mail.use(smtp, [options], [callback])

Checks an SMTP server and, when it works, makes it the server of the configuration.
ParameterTypeDescription
smtp String The host name of the SMTP server.
options? Object The connection options.
callback? Function function(err).

It calls Mail.try(); on success it sets CONF.mail_smtp and CONF.mail_smtp_options and clears the cached options. Without a callback, an error is logged with F.error().

Settings from a database
Mail.use(settings.smtp, settings.smtpoptions, function(err) {
	err && console.log('SMTP is not available', err);
});
property

Mail.debug = true

Prints the SMTP conversation to the console.

Returns Boolean

Default false. Every command sent and every reply received is printed.

Debug a server
Mail.debug = true;
event

Mail.on('error', function(err, connection) {})

Emitted when a connection or an SMTP command fails.
ParameterTypeDescription
err Error|String The error or the reply line of the server.
connection Object The internal connection object.

Not emitted for Mail.try() or for a connection reset. A message rejected by the server is passed as its reply line.

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

Mail.on('send', function(connection) {})

Emitted when a connection to the SMTP server is ready and the client starts the conversation.
ParameterTypeDescription
connection Object The internal connection object.
Count connections
Mail.on('send', function() {
	console.log('SMTP connection');
});
method

Mail.removeListener(name, fn)

Removes a handler of a Mail event.
ParameterTypeDescription
name String The event name, error or send.
fn Function The handler added with Mail.on().

Returns Mail The mail module.

Mail.once(name, fn) adds a handler that runs once; Mail.removeAllListeners([name]) removes all handlers of one event or of all events.

Stop logging
function log(err) {
	console.log(err);
}

Mail.on('error', log);
Mail.removeListener('error', log);
method

message.to(address, [name], [clear])

Adds a To recipient.
ParameterTypeDescription
address String The email address.
name? String The name of the recipient.
clear? Boolean Removes the recipients added before. Default: false

Returns MailMessage The message.

The address can contain the name: Peter Sirka <peter@example.com>. clear can be the second argument.

Two recipients
message.to('peter@example.com', 'Peter');
message.to('Lucia <lucia@example.com>');
method

message.cc(address, [name], [clear])

Adds a Cc recipient.
ParameterTypeDescription
address String The email address.
name? String The name of the recipient.
clear? Boolean Removes the Cc addresses added before. Default: false

Returns MailMessage The message.

The address can contain the name, like in message.to(). clear can be the second argument.

A copy
message.cc('office@example.com');
method

message.bcc(address, [clear])

Adds a Bcc recipient.
ParameterTypeDescription
address String The email address.
clear? Boolean Removes the Bcc addresses added before, including mail_bcc. Default: false

Returns MailMessage The message.

The address is not written to the headers. Use a plain address without a name.

A hidden copy
message.bcc('archive@example.com');
method

message.reply(address, [clear])

Adds a Reply-To address.
ParameterTypeDescription
address String The email address.
clear? Boolean Removes the reply addresses added before, including mail_reply. Default: false

Returns MailMessage The message.

Use a plain address without a name.

Replace the configured address
message.reply('billing@example.com', true);
method

message.from(address, [name])

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

Returns MailMessage The message.

The address can contain the name: My app <info@example.com>. Messages created by MAIL() and the other global functions already have the sender from mail_from and name.

Sender with a name
message.from('info@example.com', 'My app');
method

message.sender(address, [name])

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

Returns MailMessage The message.

Sender
message.sender('info@example.com', 'My app');
property

message.subject

The subject of the message.

Returns String

You can change it before the message is sent. Non-ASCII characters are encoded for you.

Prefix
message.subject = '[Test] ' + message.subject;
property

message.body

The body of the message.

Returns String

HTML by default; see message.type.

Set the body later
var message = HTMLMAIL('peter@example.com', 'Report', '');
message.manually();
render(function(html) {
	message.body = html;
	message.send2();
});
property

message.type

The content type of the body: html or plain.

Returns String

Default html. The body is sent as text/ plus this value.

A plain text message
var message = Mail.create('Hello', 'Hello,\nthis is plain text.');
message.type = 'plain';
method

message.attachment(filename, [name], [contentid])

Adds a file from the disk as an attachment.
ParameterTypeDescription
filename String The path of the file.
name? String The file name shown in the email. Default: the name of the file
contentid? String A Content-ID for an inline attachment, unique in the message.

Returns MailMessage The message.

The content type comes from the extension of name. With contentid, the file is an inline attachment and the HTML refers to it as cid:contentid. An .ics file is sent as a calendar invitation.

A PDF
message.attachment(PATH.root('invoices/2024-001.pdf'), 'invoice.pdf');
An inline image
var message = HTMLMAIL('peter@example.com', 'Report', '<img src="cid:chart1" />');
message.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');
method

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

Adds a file from a FILESTORAGE() as an attachment.
ParameterTypeDescription
storage String The name of the file storage.
id String The identifier of the file.
name? String The file name shown in the email. Default: the stored name
contentid? String A Content-ID for an inline attachment.

Returns MailMessage The message.

Without name, the name and the content type come from the stored file. A file that cannot be read is skipped and the error is logged.

A stored file
message.attachmentfs('documents', doc.fileid);
method

message.unsubscribe(url)

Adds the List-Unsubscribe headers.
ParameterTypeDescription
url String An unsubscribe URL or email address.

Returns MailMessage The message.

A URL that starts with http: or https: is used as a link; any other value is used as a mailto: address. The header List-Unsubscribe-Post: List-Unsubscribe=One-Click is added too.

A newsletter
message.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);
method

message.callback(fn)

Sets the callback of the message.
ParameterTypeDescription
fn Function function(err, message).

Returns MailMessage The message.

The callback runs when the message has been written to the server, or when the server rejects it; the error is then the reply line of the server. Connection errors are not passed here: they are logged and emitted as Mail.on('error').

Mark as sent
message.callback(function(err) {
	if (!err)
		NOSQL('orders').modify({ mailed: true }).id(order.id);
});
method

message.manually()

Stops the automatic sending of a message from MAIL(), HTMLMAIL(), LOGMAIL() or controller.mail().

Returns MailMessage The message.

Call it in the same call stack, then send the message yourself with message.send2().

Attach a generated file
var message = HTMLMAIL('peter@example.com', 'Export', '<p>The file is attached.</p>');
message.manually();

createexport(function(filename) {
	message.attachment(filename, 'export.csv');
	message.send2();
});
method

message.send2([callback])

Sends the message with mail_smtp and mail_smtp_options.
ParameterTypeDescription
callback? Function Called when the message has been written, on a new connection.

Returns MailMessage The message.

Without mail_smtp, the server is smtp. plus the domain of the sender; without a sender it throws Missing SMTP settings. While the application runs a web server, the connection is kept open for mail_smtp_keepalive; when the message goes to such an open connection, callback is not called, so prefer message.callback().

Send a created message
var message = Mail.create('Hello', '<p>Hello.</p>');
message.from(CONF.mail_from, CONF.name);
message.to('peter@example.com');
message.callback(function(err) {
	err && console.log(err);
});
message.send2();
method

message.send(smtp, options, [callback], [cache])

Sends the message to an SMTP server.
ParameterTypeDescription
smtp String The host name of the SMTP server.
options Object The connection options, the same as mail_smtp_options; pass {} for none.
callback? Function function(err, message).
cache? Boolean|Number|String Keeps the connection open, like in Mail.send(). Default: false

Returns MailMessage The message.

Uses its own connection to smtp; the configuration is not used.

Another server
message.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {
	console.log(err ? 'Failed' : 'Sent');
});
Made in Europe