Using Proxies with SMTP

Nodemailer supports out of the box HTTP and SOCKS proxies for SMTP connections with the proxy configuration option. You can also use a custom connection handler with the getSocket method.

Proxy configuration is provided as a connection url where used protocol defines proxy protocol (eg. 'socks://hostname:port' for a SOCKS5 proxy). You can also use authentication by passing proxy username and password into the configuration url (eg 'socks://username:password@hostname:port')

HTTP CONNECT tunnel

HTTP proxy must support CONNECT tunnels (also called “SSL support”) to SMTP ports. To use a HTTP/S server, provide a proxy option to SMTP configuration with the HTTP proxy configuration URL.

var smtpConfig = {
    host: 'smtp.gmail.com',
    port: 465,
    ...,
    //proxy config
    // assumes a HTTP proxy running on port 3128
    proxy: 'http://localhost:3128/'
};

Possible protocol values for the HTTP proxy:

  • 'http:' if the proxy is running in a plaintext server
  • 'https:' if the proxy is running in a secure server

NB! Proxy protocol (http/s) does not affect how SMTP connection is secured or not

See an example of using a HTTP proxy here.

SOCKS 4/5

To use a SOCKS proxy, provide a proxy option to SMTP configuration with the SOCKS4/5 proxy configuration URL.

var smtpConfig = {
    host: 'smtp.gmail.com',
    port: 465,
    ...,
    //proxy config
    // assumes a SOCKS5 proxy running on port 1080
    proxy: 'socks5://localhost:1080/'
};

NB! When using SOCKS4, only an ipv4 address can be used as proxy hostname

Possible protocol values for the SOCKS proxy:

  • 'socks4:' or 'socks4a:' for a SOCKS4 proxy
  • 'socks5:' or 'socks:' for a SOCKS5 proxy

See an example of using a SOCKS proxy here.

Custom connection handler

If you do not want to use SOCKS or HTTP proxies then you can alternatively provide a custom proxy handling code with the getSocket method. In this case you should initiate a new socket yourself and pass it to Nodemailer for usage.

// This method is called every time Nodemailer needs a new
// connection against the SMTP server
transporter.getSocket = function(options, callback){
    getProxySocketSomehow(options.port, options.host, function(err, socket){
        if(err){
            return callback(err);
        }
        callback(null, {
            connection: socket
        });
    });
};

Normally proxies provide plaintext sockets, so if the connection is supposed to use TLS then Nodemailer upgrades the socket from plaintext to TLS itself. If the socket is already upgraded then you can pass additional option secured:true to prevent Nodemailer from upgrading the already upgraded socket.

callback(null, {
    connection: socket,
    secured: true
});

See complete example using a custom socket connector here.