Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active May 27, 2021 10:14
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/d225c7adab818a6dc1dfd7783f8c8e4d to your computer and use it in GitHub Desktop.
Save tanaikech/d225c7adab818a6dc1dfd7783f8c8e4d to your computer and use it in GitHub Desktop.
Send mails from Gmail using Nodemailer

Send mails from Gmail using Nodemailer

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 :

@oshihirii
Copy link

Where do you get these values?

clientId: '### client ID ###',
clientSecret: '### client secret ###',
refreshToken: '### refresh token ###',

@De-Lac
Copy link

De-Lac commented Sep 3, 2018

I got this error :(

{ Error: Invalid status code 401
    at ClientRequest.req.on.res (/Volumes/HD Daniele/Sites/hub21/server/node_modules/nodemailer/lib/fetch/index.js:221:23)
    at emitOne (events.js:115:13)
    at ClientRequest.emit (events.js:210:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:564:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
    at TLSSocket.socketOnData (_http_client.js:453:20)
    at emitOne (events.js:115:13)
    at TLSSocket.emit (events.js:210:7)
    at addChunk (_stream_readable.js:252:12)
    at readableAddChunk (_stream_readable.js:239:11)
    at TLSSocket.Readable.push (_stream_readable.js:197:10)
    at TLSWrap.onread (net.js:589:20)
  type: 'FETCH',
  sourceUrl: 'https://accounts.google.com/o/oauth2/token',
  code: 'EAUTH',
  command: 'AUTH XOAUTH2' }

@johnnykoo84
Copy link

Hello, I get the same error with De-Lac
@De-Lac did you get any solution yet?

@SboneloMdluli
Copy link

has anyone been able to solve this

@tanaikech
Copy link
Author

In my environment, I could confirm that the script worked fine. I apologize I couldn't find about the reason that the script doesn't work.

@isaacssemugenyi
Copy link

If this problem still persists hope this link can help, it worked for me
https://codeburst.io/sending-an-email-using-nodemailer-gmail-7cfa0712a799

and below is my nodejs code
//POST route from contact form
app.post('/contact', (req, res)=>{

//Instantiate the SMTP server
const smtpTrans = nodemailer.createTransport({
	host: 'smtp.gmail.com',
	port: 465,
	secure: true,
	auth: {
		user: process.env.GMAIL_USER,
		pass: process.env.USER_PASS
	},
	tls: {
		// do not fail on invalid certs
		rejectUnauthorized: false
	}
})

//Specify what the email will look like
const mailOptions = {
	from: process.env.GMAIL_USER,
	to: process.env.RECEIVE_USER,
	subject: `${req.body.subject}`,
	text: `
		Name: ${req.body.names}
	 	Email:${req.body.email}
	 	Phone: ${req.body.phone}
	  	Message: ${req.body.text}
	  	`
}

//Attempt to send the mail
smtpTrans.sendMail(mailOptions, (err, res)=>{
	err?console.log(err):console.log('success')
})

})

all note you need body-parser and nodemailer npm installed and visit gmail settings to activate less secure apps to yes. Use the link above

@Daniel-Sogbey
Copy link

Daniel-Sogbey commented May 27, 2021

The solution by @isaacssemugenyi works only locally but does not work when your app is in production, specifically on Heroku

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment