callback is the callback function that will be run after the e-mail is sent or the sending failed (see Return callback for details)

Setting up a transport method

Before you can send any e-mails you need to set up a transport method. This can
be done with nodemailer.createTransport(type, options) where type indicates
the transport protocol and options defines how it is used.

var transport = nodemailer.createTransport("SMTP", {smtp_options});

The same transport object can and should be reused several times.

When the transport method is defined, it can be used to send e-mail with sendMail

If you want to use custom transport method, you need to provide the transport handler constructor as the type parameter. See Custom Transport Methods for details

Global transport options

In addition to any specific configuration for a selected transport type, a few global
ones exist.

resolveHostname - if set to true, resolves the public hostname for the current machine (makes an external HTTP request to remoteAddress.net for resolving it). The value is used when generating Message-ID values (as the domain part) and when identifying itself to a SMTP server

xMailer - if the value is a string it replaces the default X-Mailer header value. If the value is false then X-Mailer is stripped from the header

Setting up SMTP

SMTP is different from the other transport mechanisms, as in its case a connection
pool is created. All the connections try to stay alive as long as possible and
are reusable to minimize the protocol overhead delay - for example setting up
TLS for authenticating is relatively lengthy process (in CPU terms, not by human
terms), you do not want to do it several times.

Possible SMTP options are the following:

service - an optional well known service identifier ("Gmail", "Hotmail" etc., see Well known Services for a list of supported services) to auto-configure host, port and secure connection settings

host - hostname of the SMTP server (defaults to "localhost", not needed with service)

port - port of the SMTP server (defaults to 25, not needed with service)

secureConnection - use SSL (default is false, not needed with service). If you're using port 587 then keep secureConnection false, since the connection is started in insecure plain text mode and only later upgraded with STARTTLS

SMTP XOAUTH and token generation

XOAUTH2

nodemailer supports XOAUTH2 authentication protocol. To use this you need to obtain a Client ID and a Client Secret from Google API Console (Open "API Access" and create "Client ID for web applications") and then request a refresh token for an user. See Google OAuth 2.0 Offline Access for more information.

Once you have obtained the Client ID, Client Secret and a Refresh Token for an user, you can use these values to send mail on behalf of the user.

nodemailer includes also built in XOAUTH token generator which can be used
with nodemailer.createXOAuthGenerator(). The function is preconfigured for
Gmail, so in this case only mandatory options are user, token and tokenSecret.

Setting up Sendmail

Sendmail transport method streams the compiled message to the stdin of sendmail
command.

Options object is optional, possible sendmail options are the following:

path - path to the sendmail command (defaults to "sendmail")

args - an array of extra command line options to pass to the sendmail command (ie. ["-f", "foo@blurdybloop.com"]).

Currently the command to be spawned is built up like this: the command is either using sendmail -i -f from_addr to_addr[] (by default) or sendmail -i list_of_args[] (if args property was given). -i is ensured to be present on either case.

In the default case (no args defined) From and To addresses are either taken from From,To, Cc and Bcc properties or from the envelope property if one is present.

Be wary when using the args property - no recipients are defined by default, you need to ensure these by yourself, for example by using the -t flag.

Setting up Direct transport

Direct transport is useful when you can not or want not to use a relaying service or the sendmail command.

To set it up, you do not need to provide anything, just run the following to create a transport object:

var transport = nodemailer.createTransport();

If you want to use debug logging, use the following form:

var transport = nodemailer.createTransport("direct", {debug: true});

There is also a shorthand method mail if you do not like to set up a transport object (see E-mail message fields for options for the mailOptions object).

var mail = require("nodemailer").mail;
mail(mailOptions);

Direct can be quite inefficient as it queues all e-mails to be sent into memory. Additionally, if a message is not yet sent and the process is closed, all data about queued messages are lost. Thus direct is only suitable for low throughput systems, like password remainders and such, where the message can be processed immediatelly.

Direct is able to handle sending errors, graylisting and such. If a message can not be sent, it is requeued and retried later.

To raise the odds of getting your emails into recipients inboxes, you should setup SPF records for your domain. Using DKIM wouldn't hurt either. Dynamic IP addresses are frequently treated as spam sources, so using static IPs is advised.

Handling responses

Direct exposes an event emitter for receiving status updates. If the message includes several recipients, the message
is not sent to everyone at once but is sharded in chunks based on the domain name of the addresses. For example
if your message includes the following recipients: user1@example.com, user2@example.com and user3@blurdybloop.com, then 2 separate messages are sent out - one for user1@example.com and user2@example.com and one for user3@blurdybloop.com. This means that sending to different recipients may succeed or fail independently. All information about messages being delivered, failed or requeued is emitted by the status emitter statusHandler.

Direct exposes the following events:

'sent' - message was sent successfully

'failed' - message was failed permanently

'requeue' - message failed but the error might not be permanent, so the message is requeued for later (once the message is retried an event is fired again).

All events get the same argument which is an object with the following properties:

NB! If you want to provide instant feedback to the user, listen for the first 'sent', 'failed', or 'requeued' event only. The first event should arrive quickly but once the message gets requeued, the delay until the next event for this particular domain is fired is at least 15 minutes.

This example uses .once for listening to the events which is ok if you have just one recipient. For several recipients with different domains, the events get called several times and thus would need a more complex handling.

When would you use Direct transport?

When prototyping your application

If you do not have or do not want to use a relaying service account

When running under Windows as a Sendmail replacement (by default Sendmail is not available in Windows)

DKIM Signing

Nodemailer supports DKIM signing with very simple setup. Use this with caution
though since the generated message needs to be buffered entirely before it can be
signed. Not a big deal with small messages but might consume a lot of RAM when
using larger attachments.

Set up the DKIM signing with useDKIM method for a transport object:

transport.useDKIM(dkimOptions)

Where dkimOptions includes necessary options for signing

domainName - the domainname that is being used for signing

keySelector - key selector. If you have set up a TXT record with DKIM public key at zzz._domainkey.blurdybloop.com then zzz is the selector

privateKey - DKIM private key that is used for signing as a string

headerFieldNames - optional colon separated list of header fields to sign, by default all fields suggested by RFC4871 #5.5 are used

All messages transmitted through this transport objects are from now on DKIM signed.

Currently if several header fields with the same name exists, only the last one (the one in the bottom) is signed.

Well known services for SMTP

If you want to use a well known service as the SMTP host, you do not need
to enter the hostname or port number, just use the service parameter

Currently supported services are:

DynectEmail

Gmail

hot.ee

Hotmail

iCloud

mail.ee

Mail.Ru

Mailgun

Mailjet

Mandrill

Postmark

QQ

QQex (Tencent Business Email)

SendGrid

SES

Yahoo

yandex

Zoho

Predefined service data covers host, port and secure connection settings,
any other parameters (ie. auth) need to be set separately. Service names are
case insensitive, so using "gmail" instead of "Gmail" is totally fine.

Actually, if you are authenticating with an e-mail address that has a domain name
like @gmail.com or @yahoo.com etc., then you don't even need to provide the service name,
it is detected automatically.

As you can see the output syntax for generateTextFromHTML looks similar to markdown, and that
is exactly the case here - Nodemailer includes a simple HTML to markdown converter. But don't
expect too much from it, it's not full featured or perfect, just some regexes here and there.

Attachment fields

Attachment object consists of the following properties:

fileName - filename to be reported as the name of the attached file, use of unicode is allowed (except when using Amazon SES which doesn't like it)

Alternative fields

In addition to text and HTML, any kind of data can be inserted as an alternative content of the main body - for example a word processing document with the same text as in the HTML field. It is the job of the e-mail client to select and show the best fitting alternative to the reader.

Attahcment object consists of the following properties:

contents - String or a Buffer contents for the attachment

contentType - optional content type for the attachment, if not set will be set to "application/octet-stream"

contentEncoding - optional value of how the data is encoded, defaults to "base64"

If contents is empty, the alternative will be discarded. Other fields are optional.

The envelope only applies when using SMTP or sendmail, setting envelope has no effect with SES.

Using Embedded Images

Attachments can be used as embedded images in the HTML body. To use this
feature, you need to set additional property of the attachment - cid (unique
identifier of the file) which is a reference to the attachment file. The same
cid value must be used as the image URL in HTML (using cid: as the URL
protocol, see example below).

If you want to convert images in the HTML to embedded images automatically, you can
set mail option forceEmbeddedImages to true. In this case all images in
the HTML that are either using an absolute URL (http://...) or absolute file path
(/path/to/file) are replaced with embedded attachments.

Command line usage

Tests

There aren't currently many tests for Nodemailer but there are a lot of tests
in the modules that are used to generate the raw e-mail body and to use the
SMTP client connection.

Tweaking

Nodemailer in itself is actually more like a wrapper for my other modules
mailcomposer for composing the raw message stream
and simplesmtp for delivering it, by providing an
unified API. If there's some problems with particular parts of the
message composing/sending process you should look at the appropriate module.

License

Nodemailer is licensed under MIT license. Basically you can do whatever you want to with it.