Send mails from Gmail using Nodemailer

Gists

This is a sample script for sending e-mails from gmail using Nodemailer. In order to use this, please retrieve the folloing parameters before run this script.

  1. gmail address
  2. client ID
  3. client Secret
  4. Refresh token
    • Please include https://mail.google.com/ in the scope.
  5. Enable gmail API at API console.
  6. Install Nodemailer
const nodemailer = require('nodemailer');

var auth = {
    type: 'oauth2',
    user: '### your gmail address ###',
    clientId: '### client ID ###',
    clientSecret: '### client secret ###',
    refreshToken: '### refresh token ###',
};

var mailOptions = {
    from: '#####',
    to: '#####',
    subject: 'sample subject',
    text: 'sample text',
    html: '<b>sample html</b>',
};

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: auth,
});

transporter.sendMail(mailOptions, (err, res) => {
    if (err) {
        return console.log(err);
    } else {
        console.log(JSON.stringify(res));
    }
});

Reference :

 Share!