Nodemailer with Gmail and NodeJS
Asked Answered
T

31

162

I try to use nodemailer to implement a contact form using NodeJS but it works only on local it doesn't work on a 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('/');
        }
    });
}
Tiertza answered 9/11, 2013 at 14:43 Comment(4)
google.com/accounts/DisplayUnlockCaptcha (for visibility, posted by good commenter down below). Just allow access once and let nodemailer login automatically, it will.Dyscrasia
After trying everything to send mail via gmail using nodemailer, the following setting worked for me..Foetation
In case you're curious where the service option comes from (as I was visiting this page), the hidden documentation page is here. I call it "hidden," because it's not in the menu unless you're on that exact page. And the logo is different.Bondwoman
literally all of links are no longer available!Mealy
M
171

I solved this by going to the following url (while connected to google with the account I want to send mail from):

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

There I enabled less secure apps.

Done

Moire answered 26/11, 2014 at 23:27 Comment(5)
Well done! it is working, although I don't think it is the best idea...I got my first email..ThxPericles
with out enabling this it wont even work in local environment. he clearly mentioned that it is working in local environment and not working on remote server. what is the solution for thaat?Menis
this can't help you if you have 2FA auth in your gmail accountSingh
This is not the correct solution for productionFloriated
As of May 30, 2022, Less secure apps are not longer a feature on regular GMAIL accounts.Hitherward
H
97

See nodemailer's official guide to connecting Gmail:

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

-

It works for me after doing this:

  1. Enable less secure apps - https://www.google.com/settings/security/lesssecureapps
  2. Disable Captcha temporarily so you can connect the new device/server - https://accounts.google.com/b/0/displayunlockcaptcha
Hagan answered 25/1, 2017 at 21:34 Comment(3)
Number 2 solved my woes. I couldn't find that link anywhere in google's accounts settings. Thank you!Ojeda
Same here. I previously did #1 and got emails working on localhost, moved to production and nothing worked. #2 fixed my issue for production. Thank youApollonius
Support for less secure apps will end on May 30, 2022. See Google Help here: support.google.com/accounts/answer/… Not sure if I can still use googlemail with nodemailer.Scarletscarlett
A
76

Easy Solution:

var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');

var transporter = nodemailer.createTransport(smtpTransport({
  service: 'gmail',
  host: 'smtp.gmail.com',
  auth: {
    user: '[email protected]',
    pass: 'realpasswordforaboveaccount'
  }
}));

var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  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 apps. If this does not work then

Step 2

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

for me step 1 alone didn't 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 it gave me same error, so i had to go and turn on the less secure app (i disabled it after my work).

then for fun i just tried it with off(less secure app) and vola it worked again!

Argumentation answered 8/8, 2017 at 7:17 Comment(5)
Step 1 and 2 were very helpful. thank you! I tried step1 before i saw your solution and didn't work but with step2 its a magic!Pyrrolidine
"smptTransport is not a function"Superable
I tried with both the way you shared with us but I am getting the same error again and again { Error: connect ETIMEDOUT 74.125.68.108:465 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14) errno: 'ETIMEDOUT', code: 'ECONNECTION', syscall: 'connect', address: '74.125.68.108', port: 465, command: 'CONN' }Sven
Had to log out from my default Gmail first. Gmail for some reason does not allow you to change default account nor it does not allow you to do the second step with selected account.Devoid
2020 update: Nodemailer no longer requires the nodemailer-smtp-transport package; its built in. You can now use the above code with an object as the argument to createTransport instead of smtpTransport({}) as the argUnarm
D
55

You should use an XOAuth2 token to connect to Gmail. No worries, Nodemailer already knows about that:

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()
      }
    }
  };

You'll need to go to the Google Cloud Console to register your app. Then you need to retrieve access tokens for the accounts you wish to use. You can use passportjs for that.

Here's how it looks 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);
      });
  });
};
Dacoit answered 9/11, 2013 at 17:19 Comment(5)
Is there an easier solution to send an Email in NodeJS with a GMail account?Tiertza
#24098961Perkins
can you explain what passport.authorize does and why you need scope,callbackurl and such, why can't you just do it with clientId & secret?Lebel
passport.authorize is similar to passport.authenticate except that it doesn't attempt to update the current session. You need to pass callbackURL because after the OAuth handshake, Google needs to know where to redirect the user so the handshake gets completed.Dacoit
This should be the right solution when you are working in productionFloriated
I
26

Worked fine:

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

2- go to https://myaccount.google.com/lesssecureapps and turn on Allow less secure apps.

3- write code:

var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: 'truePassword'
    }
});

const mailOptions = {
    from: '[email protected]', // sender address
    to: '[email protected]', // 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!

Intussuscept answered 24/10, 2018 at 9:43 Comment(4)
Thanks! This was really helpful.Sandberg
Not working any more in 2023Bandstand
this no longer works 2023Kosher
Google has introduced app passwords. Use that instead of your google account password. @AwshafIshtiaquePiazza
H
17

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

Huberty answered 8/4, 2015 at 2:26 Comment(0)
H
17

Non of the above solutions worked for me. I used the code that exists in the documentation of NodeMailer. It looks like this:

let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        type: 'OAuth2',
        user: '[email protected]',
        serviceClient: '113600000000000000000',
        privateKey: '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBg...',
        accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x',
        expires: 1484314697598
    }
}); 
Harmsworth answered 27/8, 2017 at 16:1 Comment(4)
thanks Buddy ! :) thissss --- > host: 'smtp.gmail.com', port: 465, secure: true, Worked for MeChaldea
@PraveenVishnu No problem, if you vote up this answer, more people will see it. It might help them as well.Harmsworth
hi there, I know this already an old one, but would you mind where did you get serviceClient, privateKey and accessToken? Thank you.Webber
@AljohnYamaro The mail service will provide it. In my case it was Gmail. You can read more here : #36215468Harmsworth
A
16

I found the simplest method, described in this article mentioned in Greg T's answer, was to create an App Password which is available after turning on 2FA for the account.

myaccount.google.com > Sign-in & security > Signing in to Google > App Passwords

This gives you an alternative password for the account, then you just configure nodemailer as a normal SMTP service.

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

While Google recommend Oauth2 as the best option, this method is easy and hasn't been mentioned in this question yet.

Extra tip: I also found you can add your app name to the "from" address and GMail does not replace it with just the account email like it does if you try to use another address. ie.

from: 'My Pro App Name <[email protected]>'
Anemophilous answered 29/6, 2018 at 23:55 Comment(1)
Always using this1. You need to set 2-factory auth to set app password. Opposite on less secure.Unspoiled
B
15

Same problem happened to me too. I tested my system on localhost then deployed to the server (which is located at different country) then when I try the system on production server I saw this error. I tried these to fix it:

  1. https://www.google.com/settings/security/lesssecureapps Enabled it but it was not my solution
  2. https://g.co/allowaccess I allowed access from outside for a limited time and this solved my problem.
Blatant answered 28/10, 2016 at 15:44 Comment(1)
The g.co/allowaccess link was what fixed it for me (had already enabled lesssecureapps) - thanks!Reign
P
15

Many answers advice to allow less secure apps which is honestly not a clean solution.

Instead you should generate an app password dedicated to this use:

  1. Log in to your Google account
  2. Go to security
  3. Under Signing in to Google enable 2-Step Verification
  4. Under Signing in to Google click on App passwords.
  5. You'll now generate a new password. Select the app as Mail and the device as Other (Custom name) and name it.
  6. Save the app password

You can now use this app password instead of your log in password.

Phalanstery answered 23/2, 2022 at 13:41 Comment(0)
B
11

It is resolved using nodemailer-smtp-transport module inside createTransport.

var smtpTransport = require('nodemailer-smtp-transport');

var transport = nodemailer.createTransport(smtpTransport({
    service: 'gmail',
    auth: {
        user: '*******@gmail.com',
        pass: '*****password'
    }
}));
Buckle answered 24/12, 2016 at 5:59 Comment(1)
what if my password has special characters like @ should I convert them into %40?Calmas
I
10

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

Interdict answered 30/1, 2014 at 2:58 Comment(0)
A
10

For me is working this way, using port and security (I had issues to send emails from gmail using PHP without security settings)

I hope will help someone.

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: '[email protected]', // sender address
    to: '[email protected]', // 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 the config are listed here (including examples)

Ambie answered 25/6, 2016 at 9:54 Comment(0)
S
5

If you use Express, express-mailerwrapsnodemailervery nicely and is 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>
Schuck answered 22/12, 2014 at 4:19 Comment(0)
F
5

For some reason, just allowing less secure app config did not work for me even the captcha thing. I had to do another step which is enabling IMAP config:

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

  • In the top right, click Settings Settings.
  • Click Settings.
  • Click the Forwarding and POP/IMAP tab.
  • In the "IMAP Access" section, select Enable IMAP.
  • Click Save Changes.
Fic answered 6/8, 2018 at 5:47 Comment(0)
D
5

Google has disabled the Less Secure App Access, Below is New Process to use Gmail in Nodejs

  1. Now you have to enable 2 Step Verification in Google (How to Enable 2 Step Auth)
  2. You need to generate App Specific Password. Goto Google My Account > Security
  3. Click on App Password > Select Other and you will get App Password
  4. You can use normal smtp with email and App password.
Desiderata answered 19/6, 2022 at 14:28 Comment(3)
Yes google disabled the less secure app approach and the above mentioned approach can be used for SMTPDilatant
This worked properly!, less secure app is not available for two-factor authentication enabled accounts. This will be the simplest way for NodeMailer or other apps.Burial
This worked for me. The above solution is not working. I think probably because gmail has changed some of its security.Alithia
V
4

all your code is okay only the things left is just go to the link https://myaccount.google.com/security

and keep scroll down and you will found Allow less secure apps: ON and keep ON, you will find no error.

Valerianaceous answered 27/6, 2017 at 18:19 Comment(0)
D
4

Just add "host" it will work .

host: 'smtp.gmail.com'

Then enable "lesssecureapps" by clicking bellow link

https://myaccount.google.com/lesssecureapps

Dishevel answered 3/5, 2018 at 11:40 Comment(0)
W
3
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: "[email protected]",
  to: to,
  subject: subject,
  html: HTML
}
  , function (err, responseStatus) {
      if(responseStatus)
    console.log("checking dta", responseStatus.message);
    callback(err, responseStatus)
  });
});
}

You must add secureConnection type in you code.

Wino answered 7/2, 2017 at 10:45 Comment(0)
E
2

I was using an old version of nodemailer 0.4.1 and had this issue. I updated to 0.5.15 and everything is working fine now.

Edited package.json to reflect changes then

npm install
Easeful answered 16/12, 2013 at 2:35 Comment(1)
It is better to do npm update for that case. If you want to know more about how npm update and npm install different - then please see this answer - #12479179Flavio
H
2

Just attend those: 1- Gmail authentication for allow low level emails does not accept before you restart your client browser 2- If you want to send email with nodemailer and you wouldnt like to use xouath2 protocol there you should write as secureconnection:false like 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: '[email protected]',
      to:'[email protected]',
      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;
Horntail answered 15/3, 2018 at 11:27 Comment(4)
smtpTransport is used twice, which one is what ?Bunnell
Realy its very clear First one is for creating smtpTransport settings and the seccond for sending mail by using this settings its working perfectly in firebase nowdaysHorntail
Why you have used var twice for smtpTransport ?Scissors
I couldn't remember too much time but you can see that is different scope. Arrow function makes another scope this is very basic technical informationHorntail
O
2

first install nodemailer

npm install nodemailer  --save

import in to js file

const nodemailer = require("nodemailer");

const smtpTransport = nodemailer.createTransport({
    service: "Gmail",
    auth: {
        user: "[email protected]",
        pass: "password"
    },
    tls: {
        rejectUnauthorized: false
    }
});






 const mailOptions = {
        from: "[email protected]",
        to: [email protected],
        subject: "Welcome to ",
        text: 'hai send from me'.
    };


    smtpTransport.sendMail(mailOptions, function (error, response) {
        if (error) {
            console.log(error);
        }
        else {
            console.log("mail sent");
        }
    });

working in my application

Optician answered 10/8, 2018 at 12:20 Comment(0)
F
2

You may need to "Allow Less Secure Apps" in your Gmail account (it's all the way at the bottom). You also may need to "Allow access to your Google account". You also may need to "Allow access to your Google account".

Foetus answered 29/8, 2021 at 7:6 Comment(1)
This solved my problem. I no longer needed to re-sign again using the Google account web link.Christadelphian
P
2

This is my Nodemailer configuration which worked after some research.

Step 1: Enable lesssecureapp

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

Step 2: The Nodemailer configuration for Gmail

Setting up the transporter : A transporter is going to be an object that can send mail. It is the transport configuration object, connection URL, or a transport plugin instance

let transporter = nodemailer.createTransport({
    service: 'gmail',                              // the service used
    auth: {
        user: process.env.EMAIL_FROM,              // authentication details of sender, here the details are coming from .env file
        pass: process.env.EMAIL_FROM_PASSWORD,
    },
});

Writing the message

const message = {
    from: '[email protected]',                         // sender email address
    to: "[email protected], [email protected]",   // reciever email address
    subject: `The subject goes here`,
    html: `The body of the email goes here in HTML`,
    attachments: [
    {
      filename: `${name}.pdf`,
      path: path.join(__dirname, `../../src/assets/books/${name}.pdf`),
      contentType: 'application/pdf',
    },
  ],

Sending the mail

transporter.sendMail(message, function (err, info) {
    if (err) {                                            // if error
        console.log(err);
    } else {
        console.log(info);                                // if success
    }
});
Prady answered 12/4, 2022 at 11:2 Comment(0)
F
1

Less secure option is not supported anymore by gmail.

For sending email from third party, gmail is also not allowing with its user password.

You should now use App Password to resolve this issue. Hope this link will help to set your app password.

Taken from the gmail help center

Create & use app passwords

Important: To create an app password, you need 2-Step Verification on your Google Account.

If you use 2-Step-Verification and get a "password incorrect" error when you sign in, you can try to use an app password.

  1. Go to your Google Account.

  2. Select Security

  3. Under "Signing in to Google," select 2-Step Verification.

  4. At the bottom of the page, select App passwords.

  5. Enter a name that helps you remember where you’ll use the app password.

  6. Select Generate.

  7. To enter the app password, follow the instructions on your screen. The app password is the 16-character code that generates on your device.

  8. Select Done.

  9. List item

If you’ve set up 2-Step Verification but can’t find the option to add an app password, it might be because:

  • Your Google Account has 2-Step Verification set up only for security keys.
  • You’re logged into a work, school, or another organization account.
  • Your Google Account has Advanced Protection. Tip: Usually, you’ll need to enter an app password once per app or device.
Foretooth answered 26/6, 2022 at 9:8 Comment(1)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From ReviewAirdrome
V
0

I also had issues with nodemailer email sending when running on Vercel lambda in production.

What fixed it in my case was to await for sendMail Promise to resolve.

I also added nodemailer-smtp-transport like suggested in this thread but I don't think it made a difference.

Here is my whole function:

const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');


const transporter = nodemailer.createTransport(smtpTransport({
    service: 'gmail',
    auth: {
        user: '***@gmail.com',
        pass: process.env.SMTP_PASSWORD,
    },
}));


async function contact(req: any, res: any) {
    try {
        const response = await transporter.sendMail({
            from: '"*** <***gmail.com>', // sender address
            to: "***@gmail.com", // list of receivers
            subject: `***`, // Subject line
            html: `${req.body.message}<br/><br/>${req.body.firstname} ${req.body.lastname} - <b>${req.body.email}</b>`, // html body
        });
    } catch (error: any) {
        console.log(error);
        return res.status(error.statusCode || 500).json({ error: error.message });
    }

    return res.status(200).json({ error: "" });
}

export default contact;
Villalba answered 15/2, 2022 at 20:54 Comment(0)
P
0

As pointed out by Yaach, as of May 30th, 2022, Google no longer supports Less Secure Apps, and instead switched over to their own Gmail API.

Pappy answered 21/10, 2022 at 14:2 Comment(0)
T
0

Here is the sample code for Gmail SMTP with nodemailer.

"use strict";
const nodemailer = require("nodemailer");

async function main() {
    let transporter = nodemailer.createTransport({
        host: "smtp.gmail.com",
        transportMethod: "SMTP",
        secureConnection: true,
        port: 465,
        secure: true, // upgrade later with STARTTLS
        auth: {
            user: "[email protected]",
            pass: "Your App  Specific password",
        },
    });

    let info = await transporter.sendMail(
        {
            from: "[email protected]",
            to: "[email protected]",
            subject: "Testing Message Message",
            text: "I hope this message gets delivered!",
            html: "<b>Hello world?</b>", // html body
        },
        (err, info) => {
            if (err) {
                console.log(err);
            } else {
                console.log(info.envelope);
                console.log(info.messageId);
            }
        }
    );
}

main();
Thingumajig answered 26/11, 2022 at 11:35 Comment(0)
M
0

Less secure option is not supported anymore by gmail.

So you can use an App Password.

I set my 2-step verification and then get my App Password from Here (as this answer said). At the end simply ran this code with email address and that app password, then i got email with nodemailer.

const sendText = async (email, text) => {
  try {
    const transporter = nodemailer.createTransport({
      service: 'Gmail',
      auth: {
        user: process.env.EMAIL,      // ---------- my email
        pass: process.env.EMAIL_PASS, // ---------- app password
      },
    });

    const mailOptions = {
      from: process.env.EMAIL,
      to: email,
      subject: 'Some Text',
      text: `Your Text is: ${text}`,
    };

    await transporter.sendMail(mailOptions);
    return true;
  } catch (error) {
    return false;
  }
};
Mealy answered 29/3 at 13:36 Comment(0)
O
0

It's important to note that starting from September 30, 2024, Google Workspace accounts will no longer support less secure apps, third-party apps, or devices that only require username and password authentication. You can find more information at https://support.google.com/accounts/answer/6010255.

To ensure continued compatibility with Google Workspace accounts, you should switch to using OAuth2 authentication.

Here's an example of how you can configure Nodemailer to use OAuth2:

let transporter = nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  auth: {
    type: "OAuth2",
    user: "[email protected]",
    accessToken: "ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x",
  },
});

You can refer to the official documentation for more details on using OAuth2 with Nodemailer.

Ostyak answered 10/4 at 12:13 Comment(0)
C
-4

There is another option to use SendGrid for email delivery with no failure. A lot of the time, Nodemailer gives failure for mail which could happen frequently.

Nodemailer can be found in the link.

Creosote answered 17/6, 2021 at 17:57 Comment(1)
I don't think it answers the question.Mono

© 2022 - 2024 — McMap. All rights reserved.