Global mail functions, the mail configuration, the Mail module and the message object.
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.
MAIL(address, subject, view, [model], [language], [callback])| Parameter | Type | Description |
|---|---|---|
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.
MAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {
err && console.log('Not sent', err);
});
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.
HTMLMAIL(address, subject, body, [language], [callback])| Parameter | Type | Description |
|---|---|---|
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.
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.
LOGMAIL(address, [subject], body, [callback])| Parameter | Type | Description |
|---|---|---|
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.
LOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });
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.
controller.mail(address, subject, view, [model], [callback])| Parameter | Type | Description |
|---|---|---|
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.
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().
DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}| Parameter | Type | Description |
|---|---|---|
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()).
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.
ON('mail', function(message) {})| Parameter | Type | Description |
|---|---|---|
message |
MailMessage |
The message being sent. |
It is emitted for messages sent with the configuration and with Mail.send().
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.
CMD('clear_smtpcache')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.
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.
mail_smtp : smtp.example.comUsed 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.
mail_smtp : smtp.example.com
config
mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }
The options of the SMTP connection.
mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }In the config file it is a JavaScript object written as text; in code it is an object. Options:
port(default25, or465withsecure);secure(defaultfalse): TLS from the start; the options are also passed to the TLS connection;userandpassword: the login (AUTH LOGINorAUTH PLAIN, as the server offers);token: an OAuth 2.0 access token forAUTH XOAUTH2, used withuser;tls: options of the TLS connection; the client upgrades the connection withSTARTTLS;timeout(default10000): the socket timeout in milliseconds.
With user and password, a server that announces ESMTP gets STARTTLS before the login.
mail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }
mail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }
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.
mail_smtp_keepalive : 10 minutesDefault 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.
mail_smtp_keepalive : false
config
mail_from : info@example.com
The sender address of messages sent with the configuration.
mail_from : info@example.comThe sender name is the name key of the configuration. mail_address_from is an older name of this key.
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.
mail_reply : support@example.comNot used when the caller of DEF.onMail passes its own replyTo. mail_address_reply is an older name of this key.
mail_reply : support@example.com
config
mail_cc : office@example.com
A Cc address added to every message sent with the configuration.
mail_cc : office@example.commail_cc : office@example.com
config
mail_bcc : archive@example.com
A Bcc address added to every message sent with the configuration.
mail_bcc : archive@example.commail_address_copy is an older name of this key.
mail_bcc : archive@example.com
class
Mail
The global mail module: creates messages and sends them over SMTP.
MailMail 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.
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.
Mail.create(subject, body)| Parameter | Type | Description |
|---|---|---|
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().
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.
Mail.send(smtp, [options], messages, [callback], [cache])| Parameter | Type | Description |
|---|---|---|
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.
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.
Mail.send2(messages, [callback])| Parameter | Type | Description |
|---|---|---|
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.
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.
Mail.try(smtp, [options], [callback])| Parameter | Type | Description |
|---|---|---|
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.
Mail.try('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {
console.log(err ? 'Failed' : 'Works');
});
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.
Mail.use(smtp, [options], [callback])| Parameter | Type | Description |
|---|---|---|
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().
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.
Mail.debug = trueReturns Boolean
Default false. Every command sent and every reply received is printed.
Mail.debug = true;
event
Mail.on('error', function(err, connection) {})
Emitted when a connection or an SMTP command fails.
Mail.on('error', function(err, connection) {})| Parameter | Type | Description |
|---|---|---|
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.
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.
Mail.on('send', function(connection) {})| Parameter | Type | Description |
|---|---|---|
connection |
Object |
The internal connection object. |
Mail.on('send', function() {
console.log('SMTP connection');
});
method
Mail.removeListener(name, fn)
Removes a handler of a Mail event.
Mail.removeListener(name, fn)| Parameter | Type | Description |
|---|---|---|
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.
function log(err) {
console.log(err);
}
Mail.on('error', log);
Mail.removeListener('error', log);
method
message.to(address, [name], [clear])
Adds a To recipient.
message.to(address, [name], [clear])| Parameter | Type | Description |
|---|---|---|
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.
message.to('peter@example.com', 'Peter');
message.to('Lucia <lucia@example.com>');
method
message.cc(address, [name], [clear])
Adds a Cc recipient.
message.cc(address, [name], [clear])| Parameter | Type | Description |
|---|---|---|
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.
message.cc('office@example.com');
method
message.bcc(address, [clear])
Adds a Bcc recipient.
message.bcc(address, [clear])| Parameter | Type | Description |
|---|---|---|
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.
message.bcc('archive@example.com');
method
message.reply(address, [clear])
Adds a Reply-To address.
message.reply(address, [clear])| Parameter | Type | Description |
|---|---|---|
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.
message.reply('billing@example.com', true);
method
message.from(address, [name])
Sets the sender.
message.from(address, [name])| Parameter | Type | Description |
|---|---|---|
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.
message.from('info@example.com', 'My app');
method
message.sender(address, [name])
An alias of message.from().
message.sender(address, [name])| Parameter | Type | Description |
|---|---|---|
address |
String |
The email address. |
name? |
String |
The name of the sender. |
Returns MailMessage The message.
message.sender('info@example.com', 'My app');
property
message.subject
The subject of the message.
message.subjectReturns String
You can change it before the message is sent. Non-ASCII characters are encoded for you.
message.subject = '[Test] ' + message.subject;
property
message.body
The body of the message.
message.bodyReturns String
HTML by default; see message.type.
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.
message.typeReturns String
Default html. The body is sent as text/ plus this value.
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.
message.attachment(filename, [name], [contentid])| Parameter | Type | Description |
|---|---|---|
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.
message.attachment(PATH.root('invoices/2024-001.pdf'), 'invoice.pdf');
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.
message.attachmentfs(storage, id, [name], [contentid])| Parameter | Type | Description |
|---|---|---|
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.
message.attachmentfs('documents', doc.fileid);
method
message.unsubscribe(url)
Adds the List-Unsubscribe headers.
message.unsubscribe(url)| Parameter | Type | Description |
|---|---|---|
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.
message.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);
method
message.callback(fn)
Sets the callback of the message.
message.callback(fn)| Parameter | Type | Description |
|---|---|---|
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').
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().
message.manually()Returns MailMessage The message.
Call it in the same call stack, then send the message yourself with message.send2().
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.
message.send2([callback])| Parameter | Type | Description |
|---|---|---|
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().
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.
message.send(smtp, options, [callback], [cache])| Parameter | Type | Description |
|---|---|---|
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.
message.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {
console.log(err ? 'Failed' : 'Sent');
});