Nodemailer with gmail or office365

Use sendgrid or their competitors for transactional email. However, if you don’t need all the bells and whistles, then using gmail or outlook 365 suffices for low volume adhoc email. Here is a short snippet on how to set it up with node.

          import * as nodemailer from 'nodemailer';

const email = '...';
const password = '...';
const useGmail = true|false;

const smtpConnectionString = useGmail ?
    `smtps://${encodeURIComponent(email)}:${encodeURIComponent(password)}@smtp.gmail.com` :
    {
      host: 'smtp.office365.com',
      port: '587',
      auth: { user: email, pass: password },
      secureConnection: false,
      tls: { ciphers: 'SSLv3' }
    };

const mailTransport = nodemailer.createTransport(smtpConnectionString);

await mailTransport.sendMail({
      from: email,
      to: '........',
      cc: '........',
      bcc: '........',
      replyTo: email,
      subject: 'subject',
      html: 'hello world',
      text:  'hello world'
    });

        

Sendgrid use to have a transport method for nodemailer but is no longer supported. https://nodemailer.com/transports/

For GMail accounts, you will need to enable lessecureapps on the account. 1. https://www.google.com/settings/security/lesssecureapps 2. https://accounts.google.com/DisplayUnlockCaptcha