94

This is my settingController:

var sendSmtpMail = function (req,res) {
  var transport = nodemailer.createTransport({
  service:'gmail',
   auth: {
             user: "asdfqweerrccb@limitlesscircle.com",
             pass: "qwerr@wee"
        }
   });
   var mailOptions = {
        from: "transactions@limitlesscircle.com", 
        to:'umaraja1124@gmail.com', 
        subject: req.body.subject+"nodejs working ?", 
        text: "Hello world ?",  
    }
    transport.sendMail(mailOptions, function(error, response){
      if(error){
         res.send("Email could not sent due to error: "+error);
         console.log('Error');
       }else{
         res.send("Email has been sent successfully");
         console.log('mail sent');
      } 
  }); 

in postman I got the error like that:

Email could not sent due to error:

Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8  https://support.google.com/mail/?p=BadCredentials g7sm64435626pfj.29 - gsmtp
alexmac
  • 19,087
  • 7
  • 58
  • 69
uma raja
  • 1,023
  • 1
  • 7
  • 9

9 Answers9

202

Update (2022-05-02)

As mentioned in the comments and directly quoted from Google:

On May 30 2022, you may lose access to apps that are using less secure sign-in technology

So the bottom code will probably stop working with Gmail. The solution is to enable 2-Step Verification and generate Application password, then you can use the generated password to send emails using nodemailer.To do so you need to do the following:

  1. Go to your Google account at https://myaccount.google.com/
  2. Go to Security
  3. In "Signing in to Google" section choose 2-Step Verification - here you have to verify yourself, in my case it was with phone number and a confirmation code send as text message. After that you will be able to enabled 2-Step Verification
  4. Back to Security in "Signing in to Google" section choose App passwords
  5. From the Select app drop down choose Other (Custom name) and put a name e.g. nodemailer
  6. A modal dialog will appear with the password. Get that password and use it in your code.

If there is still a problem, try clearing captcha by visiting https://accounts.google.com/DisplayUnlockCaptcha from your Google account.

Sample usege

const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'YOUR-USERNAME',
        pass: 'THE-GENERATED-APP-PASSWORD'
    }
});

send();

async function send() {
    const result = await transporter.sendMail({
        from: 'YOUR-USERNAME',
        to: 'RECEIVERS',
        subject: 'Hello World',
        text: 'Hello World'
    });

    console.log(JSON.stringify(result, null, 4));
}

Old Answer (before 2022-05-02)

I think that first you need to Allow less secure apps to access account setting in your Google account - by default this settings is off and you simply turn it on. Also you need to make sure that 2 factor authentication for the account is disabled. You can check how to disable it here.

Then I use the following script to send emails from a gmail account, also tested with yahoo and hotmail accounts.

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 587,
    secure: false,
    requireTLS: true,
    auth: {
        user: 'your.gmail.account@gmail.com',
        pass: 'your.password'
    }
});

let mailOptions = {
    from: 'your.gmail.account@gmail.com',
    to: 'receivers.email@domain.example',
    subject: 'Test',
    text: 'Hello World!'
};

transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error.message);
    }
    console.log('success');
});

If you put the previous code in send-email.js for example, open terminal and write:

node send-email

You should see in the console - success, if the email was send successfully or the error message returned by nodemailer

Don't forget to first do the setting - Allow less secure apps to access account.

I hope this code will be useful for you. Good Luck!

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
codtex
  • 6,128
  • 2
  • 17
  • 34
  • this one works for me in gmail .however company domain i received Greeting never received like that – uma raja Aug 03 '17 at 10:30
  • 1
    I didn't quite understand what you are trying to say, sorry. Did you want to say that the emails are received by other gmail accounts and not but your company email accounts ? – codtex Aug 03 '17 at 10:34
  • 2
    FYI, in case you have 2F authentication enabled, then the 'less secure apps' feature is disabled. You need to generate an app password. To do that, follow these steps: support.google.com/accounts/answer/185833 – Ali Alwash Mar 05 '18 at 21:44
  • A big caveat for gmail is that you need to have 2 factor authentication turned off as well as having less secured apps allowed. Unless you provide the `auth.xoauth2` access token. It will fail otherwise. – Stuart Gough Apr 21 '20 at 14:08
  • Thanks guys for pointing this out. I've added this additional step to the explanation. – codtex Apr 21 '20 at 15:04
  • This works for me locally, but if I want to deploy my app later with something like Heroku maybe, is it possible to turn off Allow less secure apps to access account? Am I right in thinking it will be fine to turn it off because at that point my app will be using https? – Mohammed Jan 12 '21 at 22:06
  • If you turn it off this solution won't work. This code is executed on the server and doesn't care and makes no difference if you have HTTPS or not. If you want Allow less secure apps to be turned off you need to do additional configuration to use 2-Factor authentication and generate app with it's specific secret key through google account settings, which key later you can use to send emails - using 2-Factor approach saves you from putting you email password in the code and using the secret key instead. See [**other answer for 2-Factor approach**](https://stackoverflow.com/a/49306726/5452965) – codtex Jan 13 '21 at 15:18
  • 2
    This setting will no longer be available after May 30, 2022 – ibrahim Apr 18 '22 at 12:00
  • 3
    Absolutely on point for the section `Update (2022-05-02)`, thanks for sharing the right direction and steps! – Tommy Leong Jul 28 '22 at 15:12
  • Hi, i have google business account and created an alias to my email instead of myname@website.com its no-reply@website.com. i have also generated an app password. In nodemailer, in auth, i have to use my real email and app pass, in the mailoptions i entered the alias email and sent an email. the email gets sent with the real email not alias email. – kd12345 Jan 17 '23 at 10:31
  • Hi @kd12345, seems you are misunderstanding how **email aliases** are working. When you make alias it works only for the incoming messages. So in your case if someone sends email to **no-reply@website.com** you will receive it on **myname@website.com**. Email alias is not applicable for outgoing emails and you cannot sent emails for email alias. If you want to sent from **no-reply@website.com** you need to create this as actual mailbox. – codtex Jan 17 '23 at 14:24
  • I managed to get it working ill add the link i followed – kd12345 Jan 18 '23 at 05:03
47

If you have enabled 2-factor authentication on your Google account you can't use your regular password to access Gmail programmatically. You need to generate an app-specific password and use that in place of your actual password.

Steps:

  • Log in to your Google account
  • Go to My Account > Sign-in & Security > App Passwords
  • (Sign in again to confirm it's you)
  • Scroll down to Select App (in the Password & sign-in method box) and choose Other (custom name)
  • Give this app password a name, e.g. "nodemailer"
  • Choose Generate
  • Copy the long generated password and paste it into your Node.js script instead of your actual Gmail password. (You don't need the spaces.)

Your script will now look like this:

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'YOUR-GMAIL-USERNAME@gmail.com',
    pass: 'YOUR-GENERATED-APP-PASSWORD'
  }
});

I hope this helps someone.

dcdc
  • 478
  • 4
  • 4
  • 1
    just leave a website for your reference: https://support.google.com/accounts/answer/185833?hl=en – elin Jun 21 '18 at 22:15
  • 3
    In addition to this I had to do enable the captcha (link below) `https://accounts.google.com/DisplayUnlockCaptcha` then it worked for me. – NRP Sep 10 '19 at 08:21
  • Thank you so much for this answer. This was really helpful because enabling "Allow less secure apps to access account" wasn't enough. – nymphais Feb 16 '22 at 13:21
10

https://myaccount.google.com/lesssecureapps if it is OFF, turn it ON to enable lesssecureapps. (i had same issue turn it on resolve my issue)

7

In May 2022, Google removed the less secure app option (https://myaccount.google.com/lesssecureapps).

because it's risky to connect third parties to Google.

So, Gmail has provided the app password. where you can use into an app (application)

  1. Go to Google > My Account > Security > 2-step verification (just verify your number by OTP or call)
  2. Scroll down to Select App (in the Password & Sign-in Method box) and choose Other (custom name).
  3. Give this app's password a name, e.g. "nodemailer"
  4. Copy Generate password and paste it into your Node.js script instead of your actual Gmail password. (You don't need the spaces.)

Once you copied the app p/w, just register for smtp on https://www.smtper.net/ (Tick all options and don't leave any fields to fill up.) then click on "Submit" (check your Gmail account).

nodemailer code

const nodemailer = require("nodemailer");

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

var transporter = nodemailer.createTransport(
  smtpTransport({
    service: "gmail",
    host: "smtp.gmail.com",
    port: 587,
    secure: false,
    auth: {
      user: "your.gmail.account@gmail.com",
      pass: "app password",
    },
  })
);

let mailOptions = {
  from: "your.gmail.account@gmail.com",
  to: "receivers.email@domain.example",
  subject: "Test",
  text: "Hello World!",
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    return console.log(error.message);
  }
  console.log("success");
});

For a better understanding, follow the two links given below.

  1. Official SMTP: https://nodemailer.com/smtp/
  2. Setup a free Google Smtp server : https://www.youtube.com/watch?v=ql5Dex4m40w
Umanda
  • 4,737
  • 3
  • 23
  • 28
Preeti Maurya
  • 193
  • 2
  • 4
3

Make sure you are using the right port: ie port: 587 as of now.

Visit this link to allow Less secure App access: https://myaccount.google.com/lesssecureapps

Enable the recaptcha at this link: https://accounts.google.com/b/0/DisplayUnlockCaptcha

Wait for a few minutes and try to send an email.

Alternatively use sendgrid. It has a free version.

If you are not seeing the emails in your inbox, check the Spam folder.

GilbertS
  • 591
  • 8
  • 12
2

I encountered the same problem, i solved it as follows:

  1. GOTO https://admin.google.com and Login with the main account you used for setting up the business account and create users. Remember to use the main Email ID.

Main Screen after logging in

  1. Click on the Security Icon and you'll be taken to this page where you'll see Less secure apps section, click on it. enter image description here

  2. Now You'll see this, allow users or give permission here.enter image description here

  3. And you're not done yet, Not Go to the below link: https://myaccount.google.com/u/1/lesssecureapps

enter image description here

Now you'll see the switch. Enable it and try it'll definitely work.

Peace :)

Sachin R
  • 43
  • 2
2

You have to allow Less-Secure-Apps to access account settings in your google account - by default, this setting is off and you can simply turn it on. Image example

1

There are some account settings that are necessary for you to send through it using SMTP.

If you have two-step verification enabled on the account, you will need to use an application specific password (created in the Gmail account) in the device settings: Signing in using application-specific passwords

If not, please try this: sign into the Gmail account using a web browser at https://mail.google.com, then go to Settings > Accounts and Import > Other Google Account settings. Under Security, scroll down and enable access for less secure apps. This setting is required to enable SMTP, POP or IMAP access.

If there is still a problem, try clearing Captcha: visit https://accounts.google.com/DisplayUnlockCaptcha and sign in with the Gmail username and password. If necessary (it's usually not), enter the letters in the distorted picture then press Continue. This will allow ten minutes for the device to register as an approved connection. Note that you must use the account you are trying to add to the device - if the browser is already signed into another account, you must sign out first. Also, you must trigger the device to make a connection within ten minutes of pressing Continue.

Explanation from Google Support team

Pen Lymeng
  • 271
  • 5
  • 14
-1

You are using gmail service so your mail must be in gmail:

var transport = nodemailer.createTransport({
service:'gmail',
 auth: {
             user: "asdfqweerrccb@gmail.com",
             pass: "qwerr@wee"
        }
    });
var mailOptions = {
        from: "transactions@gmail.com", 
        to:'umaraja1124@gmail.com', 
        subject: req.body.subject+"nodejs working ?", 
        text: "Hello world ?",  
    }
transport.sendMail(mailOptions, function(error, response){
    if(error){
         res.send("Email could not sent due to error: "+error);
         console.log('Error');
    }else{
         res.send("Email has been sent successfully");
         console.log('mail sent');
    } 
}); 
trungducng
  • 395
  • 1
  • 7
  • 19