---
title: Sending email
project: Total.js V4
version: 0.0.99
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/mail/
updated: 2026-11-16T15:41:20.819Z
---

# Sending email

> Send email from views, HTML or logs with the SMTP server of the configuration, and send messages to any server with the Mail module.

Total.js sends email over SMTP with its own client, the `Mail` module. The global functions `MAIL()`, `HTMLMAIL()` and `LOGMAIL()` and the controller method `controller.mail()` create a message from the configuration, send it on the next tick and return it, so you can still add recipients or attachments. The full list of functions, options and message methods is in the reference of [Mail](../../reference/mail/).

## Configuration

Put the SMTP server and the sender in the `config` file:

```text
mail_smtp         : smtp.example.com
mail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }
mail_from         : info@example.com
mail_reply        : support@example.com
```

| Key | What it does |
| --- | --- |
| `mail_smtp` | The host name of the SMTP server |
| `mail_smtp_options` | The connection options, a JavaScript object written as text |
| `mail_from` | The sender address; the sender name is the `name` key of the configuration |
| `mail_reply` | A `Reply-To` address added to every message |
| `mail_cc`, `mail_bcc` | A copy of every message for this address |
| `mail_smtp_keepalive` | How long a connection stays open for the next messages (default `10 minutes`) |

The options of `mail_smtp_options`:

| Option | Default | Description |
| --- | --- | --- |
| `port` | `25`, or `465` with `secure` | The port of the server |
| `secure` | `false` | Connects with TLS from the start (SMTPS) |
| `user`, `password` | `''` | The login; the client uses `AUTH LOGIN` or `AUTH PLAIN`, as the server offers |
| `token` | `''` | An OAuth 2.0 access token, sent with `AUTH XOAUTH2` together with `user` |
| `tls` | `null` | Options for the TLS connection; the client upgrades the connection with `STARTTLS` |
| `timeout` | `10000` | The socket timeout in milliseconds |

When the server announces ESMTP and you set `user` and `password`, the client upgrades a plain connection with `STARTTLS` before it signs in, so port `587` works without `secure`:

```text
mail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }
```

Without `mail_smtp`, the framework uses `smtp.` plus the domain of the sender address. You can also check a server and save it at run time with `Mail.use()`:

```js
Mail.use('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {
	// On success, CONF.mail_smtp and CONF.mail_smtp_options are set
	err && console.log('SMTP is not available', err);
});
```

## A message from a view

`MAIL(address, subject, view, [model], [language], [callback])` renders a view from `views/` without a layout and sends the result as HTML. The model is available as `model` in the view:

```js
MAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {
	err && console.log('Not sent', err);
});
```

```html
<!-- views/mails/welcome.html -->
<p>Hello @{model.name},</p>
<p>@(your account is ready.)</p>
```

With `language`, the subject and the `@(...)` texts of the view are translated to this language. A view name such as `=green/mails/welcome` takes the view from the theme `green`.

Inside an action, `this.mail()` does the same with the language of the request:

```js
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();
}
```

`address` can be one address or an array of addresses. Each address in the array becomes a `To` recipient.

## Raw HTML and logs

`HTMLMAIL()` sends HTML that you already have. When the body has no `<body>` element, it is wrapped in a full HTML document with the subject as the title:

```js
HTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');
```

`LOGMAIL()` is for notifications to yourself. An object is serialized as JSON, and the subject defaults to the name and the version of the application:

```js
LOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });
```

## Changing the message

All these functions return the message. It is sent on the next tick, so you can change it in the same call stack:

```js
MAIL('peter@example.com', 'Invoice', 'mails/invoice', invoice)
	.cc('accounting@example.com')
	.bcc('archive@example.com')
	.reply('billing@example.com', true)
	.attachment(PATH.root('invoices/' + invoice.id + '.pdf'), 'invoice.pdf');
```

An address can contain a name: `'Peter Sirka <peter@example.com>'`, or pass the name as the second argument of `to()` and `cc()`. The `clear` argument of `to()`, `cc()`, `bcc()` and `reply()` removes the addresses added before, for example the `mail_reply` address from the configuration.

`attachment(filename, [name], [contentid])` adds a file from the disk; `attachmentfs(storage, id, [name], [contentid])` adds a file from a `FILESTORAGE()`. With `contentid`, the file is an inline attachment that the HTML refers to as `cid:`:

```js
var message = HTMLMAIL('peter@example.com', 'Report', '<img src="cid:chart1" />');
message.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');
```

To prepare a message asynchronously, stop the automatic sending with `manually()` and call `send2()` when it is ready:

```js
var message = HTMLMAIL('peter@example.com', 'Your export', '<p>The file is attached.</p>');
message.manually();

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

## Callbacks and errors

The callback of `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` and `controller.mail()` is the callback of the message: `function(err, message)`. When the SMTP server rejects the message, `err` is its reply line, for example `550 MAILBOX UNAVAILABLE`. Connection errors are logged with `F.error()` and emitted as the `error` event of `Mail`:

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

Every message emits the global event `mail` before it is written to the server, which you can use to log or audit outgoing email:

```js
ON('mail', function(message) {
	console.log('Mail to', message.address_to, message.subject);
});
```

To debug the conversation with the server, set `Mail.debug = true`; every SMTP command and reply is printed to the console.

## Sending without the configuration

The `Mail` module also sends messages to any server. `Mail.create()` creates an empty message, and `Mail.send()` sends one message or an array of messages over one connection:

```js
var message = Mail.create('Hello', '<p>Hello from the server.</p>');
message.from('info@example.com', 'My app');
message.to('peter@example.com');

Mail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], function(err) {
	err && console.log('Not sent', err);
});
```

`Mail.send2(messages, callback)` does the same with `mail_smtp` and `mail_smtp_options`. `Mail.try(smtp, [options], [callback])` only connects, signs in and quits, and returns a promise without a callback:

```js
Mail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' }).then(function() {
	console.log('SMTP works');
}).catch(function(err) {
	console.log('SMTP failed', err);
});
```

## Connections

While the application runs a web server, messages sent with the configuration reuse one connection per SMTP host for `mail_smtp_keepalive`. Set `mail_smtp_keepalive : false` to open a new connection for every message. After you change `CONF.mail_smtp` or `CONF.mail_smtp_options` in code, run `CMD('clear_smtpcache')` so the next message reads them again; `Mail.use()` and `LOADCONFIG()` do it for you.

## Message-ID

Every message has a `Message-ID` header generated by the framework. The identifier ends with the domain of the sender address, as mail servers expect, for example `<total4X...@example.com>`.
