Sending email via Node.js using nodemailer is not working

115,485

Solution 1

The answer is in the message from google.

For the second part of the problem, and in response to

I'm actually simply following the steps from the nodemailer github page so there are no errors in my code

I will refer you to the nodemailer github page, and this piece of code :

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

It differs slightly from your code, in the fact that you have : nodemailer.createTransport("SMTP". Remove the SMTP parameter and it works (just tested). Also, why encapsulating it in a http server? the following works :

var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: 'xxx',
        pass: 'xxx'
    }
});

console.log('created');
transporter.sendMail({
from: '[email protected]',
  to: '[email protected]',
  subject: 'hello world!',
  text: 'hello world!'
});

Solution 2

Outdated: refreshToken and accessToken no longer exist in JSON file output

For those who actually want to use OAuth2 / don't want to make the app "less secure", you can achieve this by

  1. Search "Gmail API" from the google API console and click "Enable"
  2. Follow the steps at https://developers.google.com/gmail/api/quickstart/nodejs. In the quickstart.js file, changing the SCOPES var from ['https://www.googleapis.com/auth/gmail.readonly'] to ['https://mail.google.com/'] in the quickstart js file provided as suggested in troubleshooting at https://nodemailer.com/smtp/oauth2/
  3. After following the steps in (2), the generated JSON file will contain the acessToken, refreshToken, and expires attributes needed in the OAuth2 Examples for Nodemailer

This way you can use OAuth2 authentication like the following

let transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        type: 'OAuth2',
        user: '[email protected]',
        clientId: '000000000000-xxx0.apps.googleusercontent.com',
        clientSecret: 'XxxxxXXxX0xxxxxxxx0XXxX0',
        refreshToken: '1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx',
        accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x',
        expires: 1484314697598
    }
});

instead of storing your gmail password in plaintext and downgrading the security on your account.

Solution 3

i just set my domain to: smtp.gmail.com and it works. I am using a VPS Vultr.

the code:

const nodemailer = require('nodemailer');
const ejs = require('ejs');
const fs = require('fs');

let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        user: '[email protected]',
        pass: 'xxx'
    }
});

let mailOptions = {
    from: '"xxx" <[email protected]>',
    to: '[email protected]',
    subject: 'Teste Templete ✔',
    html: ejs.render( fs.readFileSync('e-mail.ejs', 'utf-8') , {mensagem: 'olá, funciona'})
};

transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message %s sent: %s', info.messageId, info.response);
});

my ejs template (e-mail.ejs):

<html>
    <body>
        <span>Esse é um templete teste</span>
        <p> gerando com o EJS - <%=mensagem%> </p>
    </body>
</html>

Make sure:

have a nice day ;)

Solution 4

While the above answers do work, I'd like to point out that you can decrease security from Gmail by the following TWO steps.

STEP #1

Google Account: sign-in attempt blocked If this was you You can switch to an app made by Google such as Gmail to access your account (recommended) or change your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no longer protected by modern security standards.

STEP #2

In addition to enabling Allow less secure apps, you might also need to navigate to https://accounts.google.com/DisplayUnlockCaptcha and click continue.

Solution 5

You only need App password for google auth, then replace your google password in your code. go here https://myaccount.google.com/apppasswords

sample code:

const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
    service: "Gmail",
    auth: {
      user: '[email protected]',
      pass: 'app password here'
    }
  });
transporter.sendMail(option, function(error, info){
    if (error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }
});

screenshot

Share:
115,485
Kawd
Author by

Kawd

Updated on July 09, 2022

Comments

  • Kawd
    Kawd almost 2 years

    I've set up a basic NodeJS server (using the nodemailer module) locally (http://localhost:8080) just so that I can test whether the server can actually send out emails.

    If I understand the SMTP option correctly (please correct me if I'm wrong), I can either try to send out an email from my server to someone's email account directly, or I can send the email, still using Node.js, but via an actual email account (in this case my personal Gmail account), i.e using SMTP. This option requires me to login into that acount remotely via NodeJS.

    So in the server below I'm actually trying to use NodeJs to send an email from my personal email account to my personal email account.

    Here's my simple server :

    var nodemailer = require('nodemailer');
    var transporter = nodemailer.createTransport("SMTP", {
        service: 'Gmail',
        auth: {
            user: '*my personal Gmail address*',
            pass: '*my personal Gmail password*'
        }
    });
    
    var http = require('http');
    var httpServer = http.createServer(function (request, response)
    {
        transporter.sendMail({
           from: '*my personal Gmail address*',
           to: '*my personal Gmail address*',
           subject: 'hello world!',
           text: 'hello world!'
        });
    }).listen(8080);
    

    However, it's not working. I got an email by Google saying :

    Google Account: sign-in attempt blocked If this was you You can switch to an app made by Google such as Gmail to access your account (recommended) or change your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no longer protected by modern security standards.

    I couldn't find a solution for the above problem on the nodemailer GitHub page. Does anyone have a solution/suggestion ?

    Thanks! :-)

  • Kawd
    Kawd over 9 years
    I wanted to avoid that thinking it might actually make my account more vulnerable.. I thought I could bypass that via some nodemailer setting that I was maybe overlooking.. Maybe setting some extra certification property.. Thanks though!
  • Kawd
    Kawd over 9 years
    Having enabled that now, I know longer get that notification from Google but I don't get the email either so it's still not working I'm afraid..
  • xShirase
    xShirase over 9 years
    try using a different 'to' and 'from' address, I've had a similar issue in the past with gmail and any other recipient than myself was working.
  • Kawd
    Kawd over 9 years
    that defeats the purpose of sending emails from my site to my personal Gmail account. Creating a new Gmail account so that I can use that one as the from:in nodemailer does not make much sense, there must be some other way around that other than such a big "hack"
  • xShirase
    xShirase over 9 years
    I suggested it more as a debugging procedure, to see if the problem comes from your code or from gmail.
  • Kawd
    Kawd over 9 years
    I'm actually simply following the steps from the nodemailer github page so there are no errors in my code unfortunately. But I'll keep looking for an answer thanks!
  • Kawd
    Kawd over 9 years
    Damn! You're right, it does work! :-) Thank you so much! I'm encapsulating it in an http server because I'm basically listening for a specific URL request (that will contain the subject, email, text etc..) and then I either send the email or serve some static page. I've just omitted those other parts from here to make my code more readable..
  • Balaji Boggaram Ramanarayan
    Balaji Boggaram Ramanarayan almost 9 years
    I know that my question is irrelevant to this post. How can we send email via node mailer through open relay servers ?
  • xShirase
    xShirase almost 9 years
    @BalajiBoggaramRamanarayan If the question is irrelevant to this post, you can ask a new one on Stack Overflow
  • SuperUberDuper
    SuperUberDuper almost 8 years
    this code (for my gmail account) doesn't send anymail to me.
  • SuperUberDuper
    SuperUberDuper almost 8 years
    in fact I get no error, even if using wrong password
  • SuperUberDuper
    SuperUberDuper almost 8 years
    after looking at error I see: [Error: Invalid login: 535-5.7.8 Username and Password not accepted. even if I allow non secure acces
  • CaptRisky
    CaptRisky almost 7 years
    Is no longer valid, the accessToken and refreshToken doesn't exist in that file anymore
  • apricity
    apricity over 6 years
    To get it to work, I used a combination of this answer transport definition (without specifiying accessToken and expires) and this post which uses google's oauth playground to obtain the refresh token: medium.com/@pandeysoni/…
  • Kirby
    Kirby over 6 years
    i didn't have a SCOPES variable in my gmail-nodejs-quickstart.json
  • Harpreet Singh
    Harpreet Singh about 6 years
    don't know why, but this works on localhost, not on my staging environment
  • sasi
    sasi over 5 years
    @HarpreetSingh Hi, will it work in azure cloud environment. For me also, it is working in local, but not in cloud. It would be very much useful for me if you could update on this..
  • Harpreet Singh
    Harpreet Singh over 5 years
    @sasi, it somehow worked, but I don't remember how. sorry
  • user2101068
    user2101068 about 5 years
    @CaptRisky re: your comment "the accessToken and refreshToken doesn't exist in that file anymore" is simply inaccurate. I followed the instructions and it did indeed produce a token.json file with all of the values: access_token,refresh_token, scope, token_type and expiry_date.
  • user2101068
    user2101068 about 5 years
    @Kirby, FYI...I just followed instructions and the quickstart nodejs file did indeed have a SCOPES variable.
  • user2101068
    user2101068 about 5 years
    @ironicaldiction Hoping you might be able to give me some advice. I've followed all of the steps you outlined above but each time the Access token expires my nodejs app fails to send out the email. Specifically I get the following message response in Postman {"code": "EAUTH", "command": "AUTH XOAUTH2"}. Any thoughts?
  • mochadwi
    mochadwi about 5 years
    this also happened, when Google tries to prevent us from login. Just click "yes" to allow the sign in method from your server, so the google doesn't lock you out.
  • Kamlesh
    Kamlesh almost 5 years
    I have tried it but getting the error, "getaddrinfo ENOTFOUND Gmail" anyone can help me?
  • wilmerlpr
    wilmerlpr over 4 years
    That was the missing step: accounts.google.com/DisplayUnlockCaptcha thank you!!
  • Cezar Cobuz
    Cezar Cobuz over 4 years
    Use use port: 465 ? Does it make any difference? Also, if you have host:, does that remove the need to add service: 'Gmail' ?
  • Mathias Gheno Azzolini
    Mathias Gheno Azzolini over 4 years
    smtp default ports are: 25, 465 and 587, so port: 465 is important for make it explict. As nodemailer docs, for createTransport is not available this service property, just host;
  • Amit Patel
    Amit Patel almost 4 years
    In my case, in windows, machine mail is working perfectly fine but in the ubuntu machine, it's not working. can anyone help with this?