Node Mailer Error - node.js

I am using nodemailer in my Firebase Cloud Functions to send a mail when a data is added to the realtime database.
Code:
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const gmailEmail = 'myemail.in#gmail.com';
const gmailPassword = 'mypassword';
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: gmailEmail,
password: gmailPassword
}
});
const APP_NAME = 'ABC In'
exports.salonCreatedAccount = functions.database.instance('abc-
in').ref('/abc/{def}').onCreate(event => {
const snapshot = event.data;
const val = snapshot.val()
console.log(val);
const email = val.email;
const displayname = val.name;
return sendconfirmationEmail(email, displayname);
});
function sendconfirmationEmail(email, displayName){
const mailOptions = {
from: `${APP_NAME} <abc.in#gmail.com>`,
to: email
};
mailOptions.subject = `Welcome to ${APP_NAME}!`;
mailOptions.text = `Some Text`;
return mailTransport.sendMail(mailOptions).then(() => {
console.log(`New welcome mail sent to ${email}`);
});
}
I am getting this following error while executing.
NOTE: I have made sure that the email and password is right and there's no mistake there.
Error:
Error: Missing credentials for "PLAIN"
at SMTPConnection._formatError (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:591:19)
at SMTPConnection.login (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:340:38)
at connection.connect (/user_code/node_modules/nodemailer/lib/smtp-transport/index.js:270:32)
at SMTPConnection.once (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:188:17)
at SMTPConnection.g (events.js:292:16)
at emitNone (events.js:86:13)
at SMTPConnection.emit (events.js:185:7)
at SMTPConnection._actionEHLO (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:1113:14)
at SMTPConnection._processResponse (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:747:20)
at SMTPConnection._onData (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:543:14)
How do I fix this?

Rename password to pass in auth object. for e.g
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: gmailEmail,
pass: gmailPassword
}
});
I had the same problem, and solved it like that.
found out by diving in the code of nodemailer where this message is being logged the code look like this.
if (this._auth.user && this._auth.pass) { // this condition <---
this._auth.credentials = {
user: this._auth.user,
pass: this._auth.pass
};
} else {
return callback(this._formatError('Missing credentials for "' + this._authMethod + '"', 'EAUTH', false, 'API'));
}
Hope this helps :)

Solved same error from a local nodejs test app, by what #Zaheen replied to: Nodemailer with Gmail and NodeJS
, part of his reply is copied here:
var smtpTransport = require('nodemailer-smtp-transport');
var transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
host: 'smtp.gmail.com',
auth: {
user: 'somerealemail#gmail.com',
pass: 'realpasswordforaboveaccount'
}
}));
(BTW Accounts with 2FactorAuth cannot enable less secure apps).
I used nodemailer-smpt-transport, xoauth2, and added host to auth{}.
Haven't yet done it with Firebase, that's next ... hopefully.. :)

Using nodemailer, you have to providean email and password of the account you are sending the email from, Firebase stores that for you so you don't have to write it directly on your code.
For that to happen you have to configure the gmail.email and gmail.password Google Cloud environment variables.
In your console, within the path you store your functions /yourProject/functions$ set your variables this way:
firebase functions:config:set gmail.email="senderEmail#gmail.com" gmail.password="yourPassword"
and then you can use it this way:
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: gmailEmail,
pass: gmailPassword
}
});
I hope this is helpful for you all , it what was causing the 'missing credentialas plain error' in my case

According to the official docs, GMail may disable basic auth in some special cases.
To prevent having login issues you should either use OAuth2 or use another delivery provider and preferably a dedicated one.
Read more here: https://nodemailer.com/usage/using-gmail/

I had this same error and could not find any solution online, until now.
My solution for this exact error "Missing credentials for "PLAIN"":
Go to Authentication in Firebase Console
Click on Sign-In Method
Select Google
Make sure it is enabled
That solved my error. (Same code as you)

Related

Nodemailer - massive delay or missing emails in production

I currently have a site using Nodemailer & Gmail that works fine in my local development environment - any email sends instantly to the desired address.
Sadly, in production, only the admin notifications are being sent and the user ones are taking a very long time to deliver or not delivering at all. Ones that have arrived successfully took around 1 hour. The receiving email for admin emails is of the same domain as the URL of the website which makes me consider whether it's a domain verification issue. Only external recipients seem to get the delay.
My code is as follows:
const nodemailer = require('nodemailer')
const gmailUser = process.env.GMAIL_USER
const gmailPass = process.env.GMAIL_PASS
const appTitle = process.env.APP_TITLE
const receivingEmail = process.env.MAIL_RECEIVE
const smtpTransporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: gmailUser,
pass: gmailPass
}
})
const emailConfirmation = (userEmail) => {
const userMailOptions = {
from: appTitle,
to: userEmail,
subject: `${appTitle} - User Confirmation`
text: 'User Confirmation'
}
const adminMailOptions = {
from: appTitle,
to: receivingEmail,
subject: `${appTitle} - Admin Confirmation`,
text: 'Admin Confirmation'
}
Promise.all([
smtpTransporter.sendMail(userMailOptions),
smtpTransporter.sendMail(adminMailOptions)
])
.then((res) => { return true })
.catch((err) => { console.log("Failed to send email confirmations: ", err); return false })
}
I then call the function in a POST handler as follows:
emailConfirmation(user.email)
Am I doing something wrong in my code, or is this likely to be some sort of domain verification error?
I ended up deciding to switch to a different mail provider and have since had no issues.

How to Resolve Error Sending Email Using nodemailer googleapi?

Last week I initially posted this asking for help using nodemailer and googleapi. I'm trying to use nodemailer and googleapis to send an email. I have set up my project in https://console.cloud.google.com/ and have set my CLIENT_ID, CLIENT_SECRET, CLIENT_REDIRECT_URI and REFRESH_TOKEN in a .env and have confirmed that the values are being populated. In debug mode I have noticed the following error stack when I send the error:
'Error: invalid_grant\n at Gaxios._request (/Users/ENV/Tutoring-Invoice-Management-System/node_modules/gaxios/build/src/gaxios.js:130:23)\n at processTicksAndRejections
(node:internal/process/task_queues:96:5)\n
at async OAuth2Client.refreshTokenNoCache (/Users/ENV/Tutoring-Invoice-Management-System/node_modules/google-auth-library/build/src/auth/oauth2client.js:174:21)\n
at async OAuth2Client.refreshAccessTokenAsync (/Users/ENV/Tutoring-Invoice-Management-System/node_modules/google-auth-library/build/src/auth/oauth2client.js:198:19)\n
at async OAuth2Client.getAccessTokenAsync (/Users/ENV/Tutoring-Invoice-Management-System/node_modules/google-auth-library/build/src/auth/oauth2client.js:227:23)\n
at async sendMail (/Users/ENV/Tutoring-Invoice-Management-System/service/send-email.js:17:29)'
The code is below. I have edited it based on an answer to the question already. My question now is, why am I getting the invalid_grant error? Based on the formal documentation I have set everything up correctly in https://console.cloud.google.com/apis/credentials/oauthclient. But perhaps there is an issue there?
const nodemailer = require('nodemailer');
const { google } = require('googleapis');
require('dotenv').config();
console.log("CLIENT_ID: " + process.env.CLIENT_ID);
console.log("CLIENT_SECRET: " + process.env.CLIENT_SECRET);
console.log("CLIENT_REDIRECT_URI: " + process.env.REDIRECT_URI);
console.log("REFRESH_TOKEN: " + process.env.REFRESH_TOKEN);
const oAuth2Client = new google.auth.OAuth2(process.env.CLIENT_ID, process.env.CLIENT_SECRET, process.env.REDIRECT_URI);
console.log("oAuth2Client: " + oAuth2Client);
oAuth2Client.setCredentials({refresh_token: process.env.REFRESH_TOKEN})
async function sendMail() {
try {
const accessToken = await oAuth2Client.getAccessToken()
const transport = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
type: 'OAuth2'
}
});
const mailOptions = {
from: 'envolonakis#gmail.com',
to: 'envolonakis#gmail.com',
subject: "Test Email API Subject",
text: "Test Email API Text",
html: "<h1> Test Email API HTML </h1>",
auth: {
user: process.env.OWNER_EMAIL,
accessToken: accessToken.token
}
}
const result = await transport.sendMail(mailOptions);
return result;
} catch (error) {
console.log(error.stack);
return error;
}
}
sendMail()
From the official documentation, this is what you need to use:
try {
const accessToken = await oAuth2Client.getAccessToken()
const transport = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
type: 'OAuth2'
}
});
const mailOptions = {
from: process.env.OWNER_EMAIL,
to: process.env.RECIPIENT,
subject: "Test Email API Subject",
text: "Test Email API Text",
html: "<h1> Test Email API HTML </h1>",
auth: {
user: process.env.OWNER_EMAIL,
accessToken: accessToken.token
}
}
const result = await transport.sendMail(mailOptions);
return result;
} catch (error) {
return error;
}
One error that you have whilst using the google api authentication library is with the token. You were passing the complete token object to the auth configuration of nodemailer instead of just the access token string. Another thing to keep in mind, adding or removing parameters to the auth configuration of nodemailer will lead to different errors.
Using #Morfinismo 's solution in addition to creating a new oAuth on https://developers.google.com/oauthplayground resolved my issue.

how to send email with nodejs from heroku

I have this nodejs app am running and am trying to send an email to newly register users like a verification link. On my local server it works well but when I deployed to heroku it always fails.
my nodejs code
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
auth: {
user: 'gmail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'gmail#gmail.com',
to: email,
subject: 'Verification code',
html: `<h1 style="color:blue,font-weight:bold,text-transform-uppercase"></h1></p>
<p style="color:black,font-weight:bold,text-align:center, font-size:20px">${pin}</p>
<span>this verification process helps comfirm that your the real owner of this account, so we can
help protect you from scams</span>
<p>click the link ${v_address} to go to the verification page</p>`
};
transporter.sendMail(mailOptions, async function(error, info){
if (error) {
res.json({error:'failed please check details or network connection'});
}else {
const newCrete = await Create.save()
if(newCrete){
const newVerify = new Verifyuser({
email:email,
pin:pin,
address:v_address
})
const Verified = await newVerify.save()
res.json({success:'success'})
}
}
});
Kindly use the NPM Package (two-step-auth)
This will take care of the whole verification process, you don't need to worry about the backend work :), This will give you an OTP and the client email an OTP and you can check if they match and you can verify the Email ID,
Kindly check the full procedures with example here
Usage
const {Auth} = require('two-step-auth');
async function login(emailId){
const res = await Auth(emailId);
// You can follw the above approach, But we recommend you to follow the one below, as the mails will be treated as important
const res = await Auth(emailId, "Company Name");
console.log(res);
console.log(res.mail);
console.log(res.OTP);
console.log(res.success);
}
login("YourEmail#anyDomain.com")
Output
This will help you a lot taking care of the process of verification under the HOOD :)

Email Database Results

I have a firebase database where onCreate Google Cloud Functions calls nodemailer and sends me an email. It all works fine but now I am trying to also include the data that was added to the database in the email. I can't get it to work, seemingly because it is not in a text format and I've tried converting to text and that doesn't seem to do it. What am I doing wrong?
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: gmailEmail,
pass: gmailPassword,
},
});
exports.sendWelcomeEmail = functions.database.ref('/PickupRequests/{pushId}')
.onCreate(async(snapshot, context) => {
const val = snapshot.data;
const mailOptions = {
from: '<noreply#firebase.com>',
to: "mike#puravidalaundry.com",
subject: "New Pickup Request",
text: val //How do i convert this to a text format?
};
try {
await mailTransport.sendMail(mailOptions);
console.log('email sent');
} catch(error) {
console.error('There was an error while sending the email:', error);
}
return null;
});
To get the value from the snapshot, use snapshot.val(). So:
const val = snapshot.val();
Note that this is shown in an example in the documentation on handling event data for Realtime Database triggered Cloud Functions.
figured it out. I had to create a new variable const newvar = JSON.stringify(val) and then i said text: newvar

Sending email via Node.js using nodemailer is not working

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! :-)
The answer is in the message from google.
Go to : https://www.google.com/settings/security/lesssecureapps
set the Access for less secure apps setting to Enable
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: 'gmail.user#gmail.com',
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: 'xxx#gmail.com',
to: 'xxx#gmail.com',
subject: 'hello world!',
text: 'hello world!'
});
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
Search "Gmail API" from the google API console and click "Enable"
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/
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: 'user#example.com',
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.
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: 'xxx#gmail.com',
pass: 'xxx'
}
});
let mailOptions = {
from: '"xxx" <xxx#gmail.com>',
to: 'yyy#gmail.com',
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:
install ejs: npm install ejs --save
install nodemailer: npm install nodemailer --save
ping to smtp.gmail.com works: ping smtp.gmail.com
change xxx#gmail.com to your gmail email
change yyy#gmail.com to the email that you want to send a email
Enable less secure apps
Disable Captcha temporarily
have a nice day ;)
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.
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: 'example#gmail.com',
pass: 'app password here'
}
});
transporter.sendMail(option, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
For debugging purpose it is handy to implement a callback function (they never do on the nodemailer github page) which shows the error message (if there is one).
transporter.sendMail({
from: from,
to: to,
subject: subject,
html: text
}, function(err){
if(err)
console.log(err);
})
It helped me solve my problem... Turns out newer versions are not working properly:
"Looks like nodemailer 1.0 has breaking changes so 0.7 must be used instead: http://www.nodemailer.com/
Message posted on nodemailer as of 12/17/15:
Do not upgrade Nodemailer from 0.7 or lower to 1.0 as there are breaking changes. You can continue to use the 0.7 branch as long as you like. See the documentation for 0.7 here."
I found this answer here
And install smtp module as dependency:
npm install smtp
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
type: "SMTP",
host: "smtp.gmail.com",
secure: true,
auth: {
user: 'writeYourGmailId#gmail.com',
pass: 'YourGmailPassword'
}
});
var mailOptions = {
from: 'xyz.khan704#gmail.com',
to: 'azran.khan704#gmail.com',
subject: 'Sending Email to test Node.js nodemailer',
text: 'That was easy to test!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent');
}
});
Go to https://myaccount.google.com/lesssecureapps
and change it ON because
Some apps and devices use less secure sign-in technology, which makes your account more vulnerable. You can turn off access for these apps, which we recommend, or turn on access if you want to use them despite the risks.
You should not use gmail password for it anymore!
Recently google has provided a new method to use in 3rd party apps or APIs. You need to use App Password instead of the gmail password. But for creating it, you need to enable 2-step Authentication mode in your google account:
You can find steps here: https://support.google.com/mail/answer/185833?hl=en
try this code its work for me.
var http = require('http');
var nodemailer = require('nodemailer');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var fromEmail = 'akarthi#xyz.com';
var toEmail = 'akarthi#xyz.com';
var transporter = nodemailer.createTransport({
host: 'domain',
port: 587,
secure: false, // use SSL
debug: true,
auth: {
user: 'fromEmail#xyz.com',
pass: 'userpassword'
}
});
transporter.sendMail({
from: fromEmail,
to: toEmail,
subject: 'Regarding forget password request',
text: 'This is forget password response from your app',
html: '<p>Your password is <b>sample</b></p>'
}, function(error, response){
if(error){
console.log('Failed in sending mail');
console.dir({success: false, existing: false, sendError: true});
console.dir(error);
res.end('Failed in sending mail');
}else{
console.log('Successful in sending email');
console.dir({success: true, existing: false, sendError: false});
console.dir(response);
res.end('Successful in sending email');
}
});
}).listen(8000);
console.log('Server listening on port 8000');
response:
Successful in sending email
{ success: true, existing: false, sendError: false }
{ accepted: [ 'akarthi#xyz.com' ],
rejected: [],
response: '250 2.0.0 uAMACW39058154 Message accepted for delivery',
envelope:
{ from: 'akarthi#xyz.com',
to: [ 'akarthi#xyz.com' ] },
messageId: '1479809555147-33de4987-29d605fa-6ee150f1#xyz.com' }
Adding to xShirase answer just providing screenshots where to enable. Also confirm in security that previous attempt was from you.
Xshirase deserves all upvotes.Iam just showing screenshot.
Here is best way send email using gmail
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '******#gmail.com',
pass: '**********',
},
});
use two authentication from google => security => app password and do fill some stuff get app password

Resources