Nodemailer with Gmail and NodeJS

I am trying to use nodemailer to implement a contact form using NodeJS, but it only works on the local machine, which does not work on the remote server ...

My error message:

[website.fr-11 (out) 2013-11-09T15:40:26] { [AuthError: Invalid login - 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvlX [website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 V-dFQLgb7aRCYApxlOBuha5ESrQEbRXK0iVtOgBoYeARpm3cLZuUS_86kK7yPis7in3dGC [website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 N1sqhr3D2IYxHAN3m7QLJGukwPSZVGyhz4nHUXv_ldo9QfqRydPhSvFp9lnev3YQryM5TX [website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 XL1LZuJL7zCT5dywMVQyWqqg9_TCwbLonJnpezfBLvZwUyersknTP7L-VAAL6rhddMmp_r [website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 A_5pRpA> Please log in via your web browser and then try again. [website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787 [website.fr-11 (out) 2013-11-09T15:40:26] 534 5.7.14 54 fr4sm15630311wib.0 - gsmtp] [website.fr-11 (out) 2013-11-09T15:40:26] name: 'AuthError', [website.fr-11 (out) 2013-11-09T15:40:26] data: '534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvlX\r\n534-5.7.14 V-dFQLgb7aRCYApxlOBuha5ESrQEbRXK0iVtOgBoYeARpm3cLZuUS_86kK7yPis7in3dGC\r\n534-5.7.14 N1sqhr3D2IYxHAN3m7QLJGukwPSZVGyhz4nHUXv_ldo9QfqRydPhSvFp9lnev3YQryM5TX\r\n534-5.7.14 XL1LZuJL7zCT5dywMVQyWqqg9_TCwbLonJnpezfBLvZwUyersknTP7L-VAAL6rhddMmp_r\r\n534-5.7.14 A_5pRpA> Please log in via your web browser and then try again.\r\n534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787\r\n534 5.7.14 54 fr4sm15630311wib.0 - gsmtp', [website.fr-11 (out) 2013-11-09T15:40:26] stage: 'auth' } 

My controller:

 exports.contact = function(req, res){ var name = req.body.name; var from = req.body.from; var message = req.body.message; var to = '*******@gmail.com'; var smtpTransport = nodemailer.createTransport("SMTP",{ service: "Gmail", auth: { user: "******@gmail.com", pass: "*****" } }); var mailOptions = { from: from, to: to, subject: name+' | new message !', text: message } smtpTransport.sendMail(mailOptions, function(error, response){ if(error){ console.log(error); }else{ res.redirect('/'); } }); } 
+77
javascript nodemailer
Nov 09 '13 at 14:43
source share
22 answers

I solved this by going to the following URL (when connecting to Google with the account with which I want to send mail):

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

There I turned on less secure applications.

Done

+113
Nov 26 '14 at 23:27
source share

To connect to Gmail, you should use the XOAuth2 token. No worries, Nodemailer already knows about this:

 var smtpTransport = nodemailer.createTransport('SMTP', { service: 'Gmail', auth: { XOAuth2: { user: smtpConfig.user, clientId: smtpConfig.client_id, clientSecret: smtpConfig.client_secret, refreshToken: smtpConfig.refresh_token, accessToken: smtpConfig.access_token, timeout: smtpConfig.access_timeout - Date.now() } } }; 

To register your application, you need to go to the Google Cloud Console . Then you need to get access tokens for the accounts you want to use. You can use passports for this.

Here's what it looks like in my code:

 var passport = require('passport'), GoogleStrategy = require('./google_oauth2'), config = require('../config'); passport.use('google-imap', new GoogleStrategy({ clientID: config('google.api.client_id'), clientSecret: config('google.api.client_secret') }, function (accessToken, refreshToken, profile, done) { console.log(accessToken, refreshToken, profile); done(null, { access_token: accessToken, refresh_token: refreshToken, profile: profile }); })); exports.mount = function (app) { app.get('/add-imap/:address?', function (req, res, next) { passport.authorize('google-imap', { scope: [ 'https://mail.google.com/', 'https://www.googleapis.com/auth/userinfo.email' ], callbackURL: config('web.vhost') + '/add-imap', accessType: 'offline', approvalPrompt: 'force', loginHint: req.params.address })(req, res, function () { res.send(req.user); }); }); }; 
+36
Nov 09 '13 at 17:19
source share

See the nodemailer user guide for connecting Gmail:

https://community.nodemailer.com/using-gmail/

-

It works for me after this:

+33
Jan 25 '17 at 21:34 on
source share

A simple solution:

 var nodemailer = require('nodemailer'); var smtpTransport = require('nodemailer-smtp-transport'); var transporter = nodemailer.createTransport(smtpTransport({ service: 'gmail', host: 'smtp.gmail.com', auth: { user: 'somerealemail@gmail.com', pass: 'realpasswordforaboveaccount' } })); var mailOptions = { from: 'somerealemail@gmail.com', to: 'friendsgmailacc@gmail.com', subject: 'Sending Email using Node.js[nodemailer]', text: 'That was easy!' }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } }); 

Step 1:

go here https://myaccount.google.com/lesssecureapps and enable for less secure applications. If this does not work, then

Step 2

go here https://accounts.google.com/DisplayUnlockCaptcha and enable / continue, and then try.

for me, the first step 1 did not work, so I had to go to step 2.

I also tried removing the nodemailer-smtp-transport package and, to my surprise, it works. but then when I restarted my system, he gave me the same error, so I had to go and enable a less secure application (I turned it off after my work).

then for fun, I just tried it with the application turned off (less secure) and vola, it works again!

+24
Aug 08 '17 at 7:17
source share

I had the same problem. Enabling "less secure apps" in my Google security settings made it work!

+14
Apr 08 '15 at 2:26
source share

Try disabling captchas in your gmail account; probably triggered based on the requestor's IP address. See: How to use GMail as a free SMTP server and surpass captcha

+8
Jan 30 '14 at 2:58
source share

I work this way using port and security (I had problems sending emails from Gmail using PHP without security settings)

I hope someone helps.

 var sendEmail = function(somedata){ var smtpConfig = { host: 'smtp.gmail.com', port: 465, secure: true, // use SSL, // you can try with TLS, but port is then 587 auth: { user: '***@gmail.com', // Your email id pass: '****' // Your password } }; var transporter = nodemailer.createTransport(smtpConfig); // replace hardcoded options with data passed (somedata) var mailOptions = { from: 'xxxx@gmail.com', // sender address to: 'yyyy@gmail.com', // list of receivers subject: 'Test email', // Subject line text: 'this is some text', //, // plaintext body html: '<b>Hello world ✔</b>' // You can choose to send an HTML body instead } transporter.sendMail(mailOptions, function(error, info){ if(error){ return false; }else{ console.log('Message sent: ' + info.response); return true; }; }); } exports.contact = function(req, res){ // call sendEmail function and do something with it sendEmail(somedata); } 

all configs are listed here (including examples)

+8
Jun 25 '16 at 9:54 on
source share

The same thing happened to me. I tested my system on a local host, then deployed it to a server (which is in a different country), and then when I try to start the system on a server, I saw this error. I tried to fix them:

+8
Oct 28 '16 at 15:44
source share

This is solved using nodemailer-smtp-transport inside createTransport.

 var smtpTransport = require('nodemailer-smtp-transport'); var transport = nodemailer.createTransport(smtpTransport({ service: 'gmail', auth: { user: '*******@gmail.com', pass: '*****password' } })); 
+6
Dec 24 '16 at 5:59
source share

None of these solutions helped me. I used the code that exists in the NodeMailer documentation . It looks like this:

 let transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, auth: { type: 'OAuth2', user: 'user@example.com', serviceClient: '113600000000000000000', privateKey: '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBg...', accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x', expires: 1484314697598 } }); 
+5
Aug 27 '17 at 16:01
source share

It worked fine:

1- install nodemailer , package if not installed (type cmd): npm install nodemailer

2- Go to https://myaccount.google.com/lesssecureapps and enable Allow less secure applications .

3- write code:

 var nodemailer = require('nodemailer'); var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'trueUsername@gmail.com', pass: 'truePassword' } }); const mailOptions = { from: 'any@any.com', // sender address to: 'true@true.com', // list of receivers subject: 'test mail', // Subject line html: '<h1>this is a test mail.</h1>'// plain text body }; transporter.sendMail(mailOptions, function (err, info) { if(err) console.log(err) else console.log(info); }) 

4- enjoy!

+4
Oct 24 '18 at 9:43
source share

If you use Express, express-mailer wraps nodemailer very beautiful and very easy to use:

 //# config/mailer.js module.exports = function(app) { if (!app.mailer) { var mailer = require('express-mailer'); console.log('[MAIL] Mailer using user ' + app.config.mail.auth.user); return mailer.extend(app, { from: app.config.mail.auth.user, host: 'smtp.gmail.com', secureConnection: true, port: 465, transportMethod: 'SMTP', auth: { user: app.config.mail.auth.user, pass: app.config.mail.auth.pass } }); } }; //# some.js require('./config/mailer.js)(app); app.mailer.send("path/to/express/views/some_view", { to: ctx.email, subject: ctx.subject, context: ctx }, function(err) { if (err) { console.error("[MAIL] Email failed", err); return; } console.log("[MAIL] Email sent"); }); //#some_view.ejs <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><%= subject %></title> </head> <body> ... </body> </html> 
+3
Dec 22 '14 at 4:19
source share

all your code is in order, only the remaining things just go to the link https://myaccount.google.com/security

and continue to scroll down and you will find “Allow less secure applications: ON and continue”, you will not find an error.

+3
Jun 27 '17 at 18:19
source share

Just add a "host", it will work.

 host: 'smtp.gmail.com' 

Then enable "lesssecureapps" by clicking the link below

https://myaccount.google.com/lesssecureapps

+3
May 03 '18 at 11:40
source share
 exports.mailSend = (res, fileName, object1, object2, to, subject, callback)=> { var smtpTransport = nodemailer.createTransport('SMTP',{ //smtpTransport host: 'hostname, port: 1234, secureConnection: false, // tls: { // ciphers:'SSLv3' // }, auth: { user: 'username', pass: 'password' } }); res.render(fileName, { info1: object1, info2: object2 }, function (err, HTML) { smtpTransport.sendMail({ from: "mail@from.com", to: to, subject: subject, html: HTML } , function (err, responseStatus) { if(responseStatus) console.log("checking dta", responseStatus.message); callback(err, responseStatus) }); }); } 

You must add the secureConnection code to the code.

+2
Feb 07 '17 at 10:45
source share

For some reason, just using a less secure application configuration did not work for me, even from a security point of view. I had to take another step that includes setting up IMAP:

From the Google help page: https://support.google.com/mail/answer/7126229?p=WebLoginRequired&visit_id=1-636691283281086184-1917832285&rd=3#cantsignin

  • In the upper right corner, click Settings Settings.
  • Click Settings.
  • Click the Forwarding and POP / IMAP tab.
  • In the "IMAP Access" section, select "Enable IMAP."
  • Click Save Changes.
+2
Aug 06 '18 at 5:47
source share

I used the old version of nodemailer 0.4.1 and had this problem. I upgraded to 0.5.15, and now everything works fine.

Edited package.json to reflect changes, then

 npm install 
+1
Dec 16 '13 at 2:35
source share

Just visit these: 1- Gmail authentication, which allows low-level emails, does not accept before restarting the client’s browser. 2- If you want to send email using nodemailer and do not want to use the xouath2 protocol there, you should write as a secure connection: false as below

 const routes = require('express').Router(); var nodemailer = require('nodemailer'); var smtpTransport = require('nodemailer-smtp-transport'); routes.get('/test', (req, res) => { res.status(200).json({ message: 'test!' }); }); routes.post('/Email', (req, res) =>{ var smtpTransport = nodemailer.createTransport({ host: "smtp.gmail.com", secureConnection: false, port: 587, requiresAuth: true, domains: ["gmail.com", "googlemail.com"], auth: { user: "your gmail account", pass: "your password*" } }); var mailOptions = { from: 'from@gmail.com', to:'to@gmail.com', subject: req.body.subject, //text: req.body.content, html: '<p>'+req.body.content+' </p>' }; smtpTransport.sendMail(mailOptions, (error, info) => { if (error) { return console.log('Error while sending mail: ' + error); } else { console.log('Message sent: %s', info.messageId); } smtpTransport.close(); }); }) module.exports = routes; 
+1
Mar 15 '18 at 11:27
source share

I found the easiest way described in this article mentioned in Greg T's answer is to create an application password that will be available after enabling 2FA for the account.

myaccount.google.com> Login and Security> Google Login> Application Passwords

This gives you an alternate password for the account, then you simply configure nodemailer as a regular SMTP service.

 var smtpTransport = nodemailer.createTransport({ host: "smtp.gmail.com", port: 587, auth: { user: "username@gmail.com", pass: "app password" } }); 

Although Google recommends Oauth2 as the best option, this method is simple and not yet mentioned in this question.

Extra tip: I also found that you can add the name of your application to the "from" address, and GMail does not replace it with just the account email address, as if you were trying to use a different address. i.e.

 from: 'My Pro App Name <username@gmail.com>' 
+1
Jun 29 '18 at 23:55
source share

first nodemailer installation

 npm install nodemailer --save 

import to js file

 const nodemailer = require("nodemailer"); const smtpTransport = nodemailer.createTransport({ service: "Gmail", auth: { user: "example@gmail.com", pass: "password" }, tls: { rejectUnauthorized: false } }); const mailOptions = { from: "example@gmail.com", to: sending@gmail.com, subject: "Welcome to ", text: 'hai send from me'. }; smtpTransport.sendMail(mailOptions, function (error, response) { if (error) { console.log(error); } else { console.log("mail sent"); } }); 

works in my application

+1
Aug 10 '18 at 12:20
source share

RECOMMENDED

Here is a complete playlist for sending email with Nodejs, which includes the following:

  • Send email to Nodemailer using your Gmail account
  • Send Email Attachments
  • Send Email Templates
  • Bcc or cc people on emails
  • Send mail with MailGun + Nodemailer
  • Submit the form and receive email - Express + Nodejs + Nodemailer + MailGun

Playlist: https://www.youtube.com/playlist?list=PLurIMwd6GdCiv8ZhpqcwqpFM5Ez4JGago

Github examples: https://github.com/accimeesterlin/nodemailer-examples/tree/master/sendEmailWithGmail

Below works for this

I had the same problems until I enabled lesssecureapps in my lesssecureapps account. Make sure that you do NOT have two-step verification enabled, otherwise it may not work.

enter image description here

+1
Mar 03 '19 at 4:32
source share

this thread helps me with my problem

https://www.google.com/settings/security/lesssecureapps Enabled, but this is not my solution https://g.co/allowaccess I allowed access from the outside for a limited time, and this solved my problem.

-one
Mar 30 '17 at 22:32
source share



All Articles