Error when sending email using nodemailer - node.js

I'm trying to set up nodemailer for an app I'm creating. I'm receiving an error when I try and run the code.
This is my setup:
const nodemailer = require("nodemailer");
const xoauth2 = require("xoauth2");
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
xoauth2: xoauth2.createXOAuth2Generator({
user: '****#gmail.com',
clientId: '*******************************',
clientSecret: '*****************************',
refreshToken: '*****************************'
})
}
});
var mailOptions = {
from: 'Dave <*******#gmail.com>',
to: '*******#gmail.com',
subject: 'Nodemailer test',
text: 'Hello world'
}
transporter.sendMail(mailOptions, function(err, res) {
if (err) {
console.log(err);
} else {
console.log('Email sent');
}
})
Obviously, I've double checked my client ID, secret and refresh token. But I get the following 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 y22sm6749013wry.51 - gsmtp
at SMTPConnection._formatError (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp-connection/index.j s:557:19)
at SMTPConnection._actionAUTHComplete (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp-connection/ index.js:1248:34)
at SMTPConnection._responseActions.push.str (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp-conn ection/index.js:340:26)
at SMTPConnection._processResponse (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp-connection/ind ex.js:706:20)
at SMTPConnection._onData (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp-connection/index.js:5 09:14)
at TLSSocket._socket.on.chunk (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp- connection/index .js:461:47)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at TLSSocket.Readable.push (_stream_readable.js:134:10)
at TLSWrap.onread (net.js:551:20)
code: 'EAUTH',
response: '535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8 https://support.google.com/mail/?p=BadCrede ntials y22sm6749013wry.51 - gsmtp',
responseCode: 535,
command: 'AUTH PLAIN' }
This is the first time I've tried using nodemailer and I feel I'm obviously missing a key piece here but not sure what.
New error when using real email and password:
{ Error: Invalid login: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbvZ
534-5.7.14 vX8SWYwnciMLBvsoC9zLFxi_9pKu2juDkWdPY4cJngQct2L0qjKFr3aF_SlAVCV816xj-8
534-5.7.14 eC36n8fZzITno-GnJdvwRSf6eIXfeU_ohzp07tc4S3LA0x2k9xPRwAjMlsWfNoa1Iz2GwX
534-5.7.14 AyBKjwT8nmD-wpNNK5J_bN9F3OI56XFAfw0NmjxKnUfhHXPoTs0sGCc6eRn_9hgYp2TyFe
534-5.7.14 MAd2gvxDCVp5O9V-yuGa9nrch8ey4> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 f135sm7148225wmd.7 - gsmtp
at SMTPConnection._formatError (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp- connection/index.js:557:19)
at SMTPConnection._actionAUTHComplete (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp- connection/index.js:1248:34)
at SMTPConnection._responseActions.push.str (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp-connection/index.js:340:26)
at SMTPConnection._processResponse (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp-connection/index.js:706:20)
at SMTPConnection._onData (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp-connection/index.js:509:14)
at TLSSocket._socket.on.chunk (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/nodemailer/lib/smtp-connection/index.js:461:47)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at TLSSocket.Readable.push (_stream_readable.js:134:10)
at TLSWrap.onread (net.js:551:20)
code: 'EAUTH',
response: '534-5.7.14 Please log in via your web browser and\n534-5.7.14 then try again.\n534-5.7.14 Learn more at\n534 5.7.14 https://support.google.com/mail/answer/78754 f135sm7148225wmd.7 - gsmtp',
responseCode: 534,
command: 'AUTH PLAIN' }

You need to set up the transporter differently, using the actual email and password of a real Google Account.
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'somerealemailaddress#gmail.com', //email address to send from
pass: 'somerealemailpassword' //the actual password for that account
}
});

Similar question
Sample code: OAuth2 in Nodemailer
var email_smtp = nodemailer.createTransport({
host: "smtp.gmail.com",
auth: {
type: "OAuth2",
user: "youremail#gmail.com",
clientId: "CLIENT_ID_HERE",
clientSecret: "CLIENT_SECRET_HERE",
refreshToken: "REFRESH_TOKEN_HERE"
}
});

const xoauth2 = require("xoauth2");
Actually in my case i didn't make use of the above code which i have mentioned and yet it worked fine...Just changed the google settings from the link sent in the error and it was fine.
But i get the error especially when i try to use yahoo as the service provider instead of google.I have attached a screenshot of the error which i get for your reference.
The error which i get while using yahoo as service provider

I can see and easy way in other post. I only click accounts.google.com/DisplayUnlockCaptcha
from; Nodemailer with Gmail service not working on heroku

Related

SMTP ERROR using Nodemailer to send email

i am building a web app and i want to send emails to registered users that forgot their password. But I am having problem with sending the mail through Node mail. I keep getting a 421 response error that the server is busy with too many connections ans i dont understand why.
below is my code and the error i keep getting.
require('dotenv').config()
const nodeMailer = require('nodemailer')
const sendMail = async (email, token) => {
const transporter = nodeMailer.createTransport({
host: process.env.EMAIL_HOST,
port: 587,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASSWORD,
},
});
console.log("passed transportrt ");
await transporter.sendMail({
from: process.env.EMAIL_USER,
to: email,
subject: "Password RESET",
text: `Follow this link to reset your password. It expires in 15minutes. \n\n
http://localhost:4000/reset/${token}`,
});
console.log('out')
}
module.exports = sendMail
the other parts and work flow works well till it gets to await transporter.sendMail({...
and this is the error i keep getting below
Error: Invalid greeting. response=421 Service not available: 421 Service not available
at SMTPConnection._actionGreeting (.../node_modules/nodemailer/lib/smtp-connection/index.js:1205:27)
at SMTPConnection._processResponse (.../node_modules/nodemailer/lib/smtp-connection/index.js:947:20)
at SMTPConnection._onData (.../node_modules/nodemailer/lib/smtp-connection/index.js:749:14)
at Socket.SMTPConnection._onSocketData (.../node_modules/nodemailer/lib/smtp-connection/index.js:189:44)
at Socket.emit (node:events:526:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
code: 'EPROTOCOL',
response: '421 Service not available',
responseCode: 421,
command: 'CONN'
}
Is there something i am possibly doing wrong? Plus i am running this on unbuntu(if it has any connection to the error)
A 421 error with an EPROTOCOL error usually means the mail client could not connect to the mail server. Two easy possibilities to check:
process.env.EMAIL_HOST is not defined (not set in .env file or OS)
Your server cannot connect to the mail host at port 587 (easily checked with telnet).

535 Authentication Credentials Invalid in Node.js

I am using node mailer with smtp-pool to sending Mail When I run the app I get this error.
my user and pass and host every thing is right but i face this error.
email.js
const nodemailer = require("nodemailer");
var smtpPool = require('nodemailer-smtp-pool');
const sendEnquiryEmail = function (enquiryData) {
let FromUserName = 'Chat2cars';
nodemailer.createTestAccount((err, account) => {
var transporter = nodemailer.createTransport(smtpPool({
host: 'smtp.gmail.com',
port: 587,
auth: {
user: 'user#gmail.com',
pass: 'mypass'
},
maxConnections: 5,
maxMessages: 10
}));
module.exports = {
sendEnquiryEmail: sendEnquiryEmail
}
And i face this Error
Error: Invalid login: 535 Authentication Credentials Invalid
at SMTPConnection._formatError (D:\CHAT_CAR\Node\node_modules\smtp-connection\lib\smtp-connection.js:528:15)
at SMTPConnection._actionAUTHComplete (D:\CHAT_CAR\Node\node_modules\smtp-connection\lib\smtp-connection.js:1231:30)
at SMTPConnection.<anonymous> (D:\CHAT_CAR\Node\node_modules\smtp-connection\lib\smtp-connection.js:319:22)
at SMTPConnection._processResponse (D:\CHAT_CAR\Node\node_modules\smtp-connection\lib\smtp-connection.js:669:16)
at SMTPConnection._onData (D:\CHAT_CAR\Node\node_modules\smtp-connection\lib\smtp-connection.js:493:10)
at TLSSocket.emit (events.js:210:5)
at addChunk (_stream_readable.js:308:12)
at readableAddChunk (_stream_readable.js:289:11)
at TLSSocket.Readable.push (_stream_readable.js:223:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:182:23) {
code: 'EAUTH',
response: '535 Authentication Credentials Invalid',
responseCode: 535,
command: 'AUTH PLAIN'
}```
Solutions in order of likelihood to help.
Double check you have the correct password 😊
Check if the user has 2fa enabled if so you will need an apps password
Check your Captcha loc
Look into Xoauth2

Why nodemailer give me this error when I try to send an e-mail using gmail address? Error: Can't set headers after they are sent

I am working on a Firebase project that uses Google Cloud Functions. I am some problem trying to implement a cloud function that uses nodemailer in order to send an e-mail.
I have something like this in my code:
import * as functions from 'firebase-functions';
import admin = require('firebase-admin');
import nodemailer = require('nodemailer');
admin.initializeApp();
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: 'my-sender-mail#gmail.com',
pass: 'my-password'
}
});
const mailOptions = {
from: `my-sender-mail#gmail.com`,
to: `my-destination-mail#gmail.com`,
subject: 'contact form message',
text: 'TEST TEST TEST'
/*
html: `<h1>Order Confirmation</h1>
<p> <b>Email: </b>TEST </p>`
*/
};
export const sendEmailNotification = functions.https.onRequest((request, response) => {
console.log("sendEmailNotification START 2");
transporter.sendMail(mailOptions, (error, data) => {
if (error) {
console.log(error);
response.status(500).json({message: 'ERROR SENDING MAIL !!!'});
}
console.log("Sent!");
response.status(200).json({message: 'NOTIFICATION MAIL SENT !!!'});
});
});
So as you can see I prepared the transporter object setting the gmail confifuration inserting user and password as authentication.
Then the maulOption object contains the e-mail to be sent.
Finnally I defined a GET function that called should send the e-mail.
The problem is that it is not working and I am obtaining the following error into the Firebase cloud function log:
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (/worker/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/worker/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/worker/node_modules/express/lib/response.js:267:15)
at transporter.sendMail (/srv/lib/index.js:72:30)
at transporter.send.args (/srv/node_modules/nodemailer/lib/mailer/index.js:226:21)
at connection.login.err (/srv/node_modules/nodemailer/lib/smtp-transport/index.js:282:36)
at SMTPConnection._actionAUTHComplete (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:1513:20)
at SMTPConnection._responseActions.push.str (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:540:26)
What it means? What is wrong? What am I missing? I am going crazy...how can I fix my code in order to correctly send this e-mail?
EDIT-1: After that I solved the header error I am obtaining this new error message:
{ 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 t12sm13191635ios.12 - gsmtp
at SMTPConnection._formatError (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:774:19)
at SMTPConnection._actionAUTHComplete (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:1513:34)
at SMTPConnection._responseActions.push.str (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:540:26)
at SMTPConnection._processResponse (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:932:20)
at SMTPConnection._onData (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:739:14)
at TLSSocket.SMTPConnection._onSocketData.chunk (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:189:44)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
code: 'EAUTH',
response: '535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8 https://support.google.com/mail/?p=BadCredentials t12sm13191635ios.12 - gsmtp',
responseCode: 535,
command: 'AUTH PLAIN' }
EDIT-2: As suggested I actevated also the Less secure app access but now I obtain this error message into the Firebase cloud function log:
{ Error: Invalid login: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs
534-5.7.14 XR1smQTqgOc7rRSUWEDTn9TfUIueWg5Fyd78-WkCR0YjjNDoMp91N1f4Lwy0EE9YKy720
534-5.7.14 Eg9dGeLWkuox0l8KKoOB2GdveIVKleuQ7mO5oYJT6ZMLdk-EzDxujYyknc_YmpkV>
534-5.7.14 Please log in via your web browser and then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 m26sm16711541ill.21 - gsmtp
at SMTPConnection._formatError (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:774:19)
at SMTPConnection._actionAUTHComplete (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:1513:34)
at SMTPConnection._responseActions.push.str (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:540:26)
at SMTPConnection._processResponse (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:932:20)
at SMTPConnection._onData (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:739:14)
at TLSSocket.SMTPConnection._onSocketData.chunk (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:189:44)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
code: 'EAUTH',
response: '534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n534-5.7.14 XR1smQTqgOc7rRSUWEDTn9TfUIueWg5Fyd78-WkCR0YjjNDoMp91N1f4Lwy0EE9YKy720\n534-5.7.14 Eg9dGeLWkuox0l8KKoOB2GdveIVKleuQ7mO5oYJT6ZMLdk-EzDxujYyknc_YmpkV>\n534-5.7.14 Please log in via your web browser and then try again.\n534-5.7.14 Learn more at\n534 5.7.14 https://support.google.com/mail/answer/78754 m26sm16711541ill.21 - gsmtp',
responseCode: 534,
command: 'AUTH PLAIN' }
The fix should be pretty simple; At the moment, you're setting the response status twice, this is what is causing the issue in the logs.
Changing the transporter.sendMail callback like to should fix this:
transporter.sendMail(mailOptions, (error, data) => {
if (error) {
console.log(error);
response.status(500).json({message: 'ERROR SENDING MAIL !!!'});
} else {
console.log("Sent!");
response.status(200).json({message: 'NOTIFICATION MAIL SENT !!!'});
}
});
I suspect there's another error sending the mail as well, but it won't be logged until you're able to fix this one.
I believe you'll also need to configure the gmail account to accept logins from nodemailer.
If your account is using 2FA, then you need to use app password, instead of your regular password you use on web. You can read more about it here.
There might be another way to give access by enabling less secure apps but as name suggest it is not recommended, but for testing purposes you can try to enable it. Read more about it here.
EDIT
You might also need to Unlock Captcha in order to gain access. Try this link.

Nodemailer EAUTH 535 5.7.3 Authentication unsuccessful on Azure Ubuntu server but not local server

I have an Azure Ubuntu 18.04 server with Node v12.13.1, my local machine is Windows 10 and node v10.16.0.
When I run on my local computer there is no issue with Nodemailer sending the email, it sends and quickly appears in my email.
However when it is run on my Azure server, I get the following error.
Error: Invalid login: 535 5.7.3 Authentication unsuccessful [BY5PR16CA0034.nampr d16.prod.outlook.com]
at SMTPConnection._formatError (/home/user/EMR/node_modules/nodemailer/l ib/smtp-connection/index.js:784:19)
at SMTPConnection._actionAUTHComplete (/home/user/EMR/node_modules/nodem ailer/lib/smtp-connection/index.js:1523:34)
at SMTPConnection.<anonymous> (/home/user/EMR/node_modules/nodemailer/li b/smtp-connection/index.js:1481:18)
at SMTPConnection._processResponse (/home/user/EMR/node_modules/nodemail er/lib/smtp-connection/index.js:942:20)
at SMTPConnection._onData (/home/user/EMR/node_modules/nodemailer/lib/sm tp-connection/index.js:749:14)
at TLSSocket.SMTPConnection._onSocketData (/home/user/EMR/node_modules/n odemailer/lib/smtp-connection/index.js:195:44)
at TLSSocket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10) {
code: 'EAUTH',
response: '535 5.7.3 Authentication unsuccessful [BY5PR16CA0034.namprd16.prod. outlook.com]',
responseCode: 535,
command: 'AUTH LOGIN'
}
Here is the code for running Nodemailer on my node.js server:
let transport = nodemailer.createTransport({
service: "Outlook365",
auth: {
user: process.env.USER,
pass: process.env.PASS
},
tls:{
rejectUnauthorized: false
}
})
let message = {
from: '"Name Apps" <nameapps#name.org>',
to: item.email,
subject: subjectText,
html: `<b>HTML message</b>`
};
transport.sendMail(message, function(err, info) {
if (err) {
console.log(err)
} else {
console.log(info);
}
});

Nodemailer and GMail OAuth: Username and Password not accepted

So i have the following codes:
const nodemailer = require("nodemailer");
const mailer = {
service: "gmail",
auth: {
type: "OAuth2",
user: "mailtester123123123#gmail.com",
clientId: "123123123123123123123123123123.apps.googleusercontent.com",
clientSecret: "krW123123123123123123RqEnS",
refreshToken: "1/SM-7f31231231231231231231231231231231231231231231231UzH",
accessToken: "ya29.1234568791231324564897894231324564697897ss3Ggi-TkWO4HSIZBqHiLpoIkT7H_Sgii4RQxyVJ0QjIfjKB5zk"
}
}
const transporter = nodemailer.createTransport(mailer);
transporter.sendMail({
to: "mailtester123123123#windowslive.com",
subject: "test",
text: "test"
});
But when i try to send email, it always give error as follow: 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 f67-v6sm75536287pfe.75 - gsmtp
This is the full trace:
(node:25324) UnhandledPromiseRejectionWarning: 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 f67-v6sm75536287pfe.75 - gsmtp
at SMTPConnection._formatError (D:\Sources\NodeJS\test\node_modules\nodemailer\lib\smtp-connection\index.js:606:19)
at SMTPConnection._actionAUTHComplete (D:\Sources\NodeJS\test\node_modules\nodemailer\lib\smtp-connection\index.js:1335:34)
at SMTPConnection._responseActions.push.str (D:\Sources\NodeJS\test\node_modules\nodemailer\lib\smtp-connection\index.js:1314:26)
at SMTPConnection._processResponse (D:\Sources\NodeJS\test\node_modules\nodemailer\lib\smtp-connection\index.js:762:20)
at SMTPConnection._onData (D:\Sources\NodeJS\test\node_modules\nodemailer\lib\smtp-connection\index.js:558:14)
at TLSSocket._socket.on.chunk (D:\Sources\NodeJS\test\node_modules\nodemailer\lib\smtp-connection\index.js:510:47)
at TLSSocket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
at TLSSocket.Readable.push (_stream_readable.js:219:10)
Any idea what happened and how to fix this? Thank you.
This error occurs when you are trying to access Google account and forget to switch on Google less security option. Do following changes:
https://myaccount.google.com/lesssecureapps?utm_source=google-account&utm_medium=web
I had this error and my mistake was that I was trying to give only this permission:
"https://www.googleapis.com/auth/gmail.send"
I fixed it by giving the full permissions:
"https://mail.google.com/"
I'm talking about the scopes used to generate the tokens on https://developers.google.com/oauthplayground/

Resources