Setup SMTP

Why do I have to setup anything while PHP’s mail() function works out of the box? Read here

You can use 3 kinds of different approaches when using SMTP

  1. normal usage. No specific configuration needed. For every e-mail a new SMTP connection is created and message is sent immediately. Used when the amount of sent messages is low.
  2. pooled usage. Set pool option to true to use it. A fixed amount of pooled connections are used to send messages. Useful when you have a large number of messages that you want to send in batches.
  3. direct usage. Set direct option to true to use it. SMTP connection is opened directly to recipients MX server, skipping any local SMTP relays. useful when you do not have a SMTP relay to use. Riskier though since messages from untrusted servers usually end up in the Spam folder.

All SMTP connections allow to use proxies for making connections. Read about proxy support in Nodemailer from here

var transporter = nodemailer.createTransport(options[, defaults])

Where

options defines connection data
* options.pool if set to true uses pooled connections (defaults to false), otherwise creates a new connection for every e-mail.
* options.direct if set to true, bypasses MTA relay and connects directly to recipients MX. Easier to set up but has higher chances of ending up in the Spam folder
* options.service can be set to the name of a well-known service so you don’t have to input the port, host, and secure options (see Using well-known services)
* options.port is the port to connect to (defaults to 25 or 465)
* options.host is the hostname or IP address to connect to (defaults to 'localhost')
* options.secure if truethe connection will only use TLS. If false (the default), TLS may still be upgraded to if available via the STARTTLS command.
* options.ignoreTLS if this is true and secure is false, TLS will not be used (either to connect, or as a STARTTLS connection upgrade command).
* options.requireTLS if this is true and secure is false, it forces Nodemailer to use STARTTLS even if the server does not advertise support for it.
* options.tls defines additional node.js TLSSocket options to be passed to the socket constructor, eg. {rejectUnauthorized: true}.
* options.auth defines authentication data (see authentication section below)
* options.authMethod defines preferred authentication method, eg. ‘PLAIN’
* options.name optional hostname of the client, used for identifying to the server
* options.localAddress is the local interface to bind to for network connections
* options.connectionTimeout how many milliseconds to wait for the connection to establish
* options.greetingTimeout how many milliseconds to wait for the greeting after connection is established
* options.socketTimeout how many milliseconds of inactivity to allow
* options.logger optional bunyan compatible logger instance. If set to true then logs to console. If value is not set or is false then nothing is logged
* options.debug if set to true, then logs SMTP traffic, otherwise logs only transaction events
* options.maxConnections available only if pool is set to true. (defaults to 5) is the count of maximum simultaneous connections to make against the SMTP server
* options.maxMessages available only if pool is set to true. (defaults to 100) limits the message count to be sent using a single connection. After maxMessages messages the connection is dropped and a new one is created for the following messages
* options.rateLimit available only if pool is set to true. (defaults to false) limits the message count to be sent in a second. Once rateLimit is reached, sending is paused until the end of the second. This limit is shared between connections, so if one connection uses up the limit, then other connections are paused as well
* options.disableFileAccess if true, then does not allow to use files as content. Use it when you want to use JSON data from untrusted source as the email. If an attachment or message node tries to fetch something from a file the sending returns an error
* options.disableUrlAccess if true, then does not allow to use Urls as content

Examples

var smtpConfig = {
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL
    auth: {
        user: '[email protected]',
        pass: 'pass'
    }
};

var poolConfig = {
    pool: true,
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL
    auth: {
        user: '[email protected]',
        pass: 'pass'
    }
};

var directConfig = {
    name: 'hostname' // must be the same that can be reverse resolved by DNS for your IP
};

Alternatively you could use connection url. Use smtp:, smtps: or direct: as the protocol.

var smtpConfig = 'smtps://user%40gmail.com:[email protected]';
var poolConfig = 'smtps://user%40gmail.com:[email protected]/?pool=true';
var directConfig = 'direct:?name=hostname';

Events

Event:’idle’

Applies to pooled SMTP connections. Emitted by the transport object if connection pool has free connection slots. Check if a connection is still available with isIdle() method (returns true if a connection is still available). This allows to create push-like senders where messages are not queued into memory in a Node.js process but pushed and loaded through an external queue like RabbitMQ.

var messages = [...'list of messages'];
transporter.on('idle', function(){
    // send next messages from the pending queue
    while(transporter.isIdle() && messages.length){
        transporter.send(messages.shift());
    }
});

Authentication

If authentication data is not present, the connection is considered authenticated from the start. Set authentication data with options.auth

  • auth is the authentication object
    • auth.user is the username
    • auth.pass is the password for the user
    • auth.xoauth2 is the OAuth2 access token (preferred if both pass and xoauth2 values are set) or an XOAuth2 token generator object.

See the docs for using OAuth2 with Nodemailer here.

Using well-known services

If you do not want to specify the hostname, port and security settings for a well known service, you can use it by its name, see the documentation and supported services here.

Verify SMTP connection configuration

You can verify your SMTP configuration with verify(callback) call (also works as a Promise). If it returns an error, then something is not correct, otherwise the server is ready to accept messages.

// verify connection configuration
transporter.verify(function(error, success) {
   if (error) {
        console.log(error);
   } else {
        console.log('Server is ready to take our messages');
   }
});