Send mail using Node.js with nodemailer in 2 mins

Sean Chen
3 min readJan 23, 2017

--

Step-to-step tutorial

Basics:

  • nodejs(5.6.0), nodemailer(0.7.1)
  • nodemailer is a nodejs package for sending mail.
  • requires basic knowledge of Google Console, nodejs

Using the example on nodemailer official page might not going reveal the “IT JUST WORKS” moment. So here is the step-to-step tutorial that actually works.

Step 1: Add this to your package.json

"nodemailer": "^0.7.1",

Step 2: Create a client in Google Console

Google Console → API Manager → Credentials → Create credentials → OAuth client ID

Then, Choose “Web Application”, enter “https://developers.google.com/oauthplayground” in “Authorized redirect URLs”

We are going to use OAuthPlayground to retrieve related tokens and use it in our code. The clientId and clientSecret will be use later.

Step 3: Use Google OAuth 2.0 playground to get refresh_token

Here is the entry: https://developers.google.com/oauthplayground/

First go the the top-right corner where you can find a “OAuth 2.0 Configuration” button.

And change your configs like mine. Enter the clientId and clientSecret below.

On the left of the whole page: Type “https://mail.google.com/” into the scope input. And press “Authorize APIs

And then press the “Exchange authorization code for tokens” button.

And that’s it! 🙌🏼 You’ve got “Refresh token”!

Step 4: Use clientId, clientSecret and refresh token in the code. Here’s the snippet.

// Create a Transport instance using nodemailer
var nodemailer = require('nodemailer');
sails.log.debug('try to send mail');var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Gmail",
auth: {
XOAuth2: {
user: "xxx@gmail.com", // Your gmail address.
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
refreshToken: "REFRESH_TOKEN_YOU_JUST_FOUND"
}
}
});
// Setup mail configuration
var mailOptions = {
from: 'xxx@gmail.com', // sender address
to: RECEIVER_EMAIL", // list of receivers
subject: 'A_SUBJECT', // Subject line
// text: '', // plaintext body
html: htmlBody // html body
};
// send mail
smtpTransport.sendMail(mailOptions, function(error, info) {
if (error) {
sails.log.debug(error);
return res.notOk({
status: 'error',
msg: 'Email sending failed'
})
} else {
console.log('Message %s sent: %s', info.messageId, info.response);
return res.ok({
status: 'ok',
msg: 'Email sent'
})
}
smtpTransport.close();
});

Optional Step: Go to Google account settings to allow “less secure apps”

https://www.google.com/settings/u/2/security/lesssecureapps

That’s it! email me or leave a comment below if you have any questions, Thanks for reading. sean@appar.com.tw

Follow me on Twitter: SeanChenU

Looking for developers? checkout this agency https://appar.com.tw

--

--

Sean Chen

An iOS/ Android/React Native developer. Write Python Django. Founder of Appar Technologies. Deliver high quality software swiftly. https://appar.com.tw