How to send mail using Nodemailer in Node.js - node.js

I tried to send e-mail using Nodemailer in Node.js but it is not working. I don't know why it is not working. If anyone knows, please help, to find the solution.
Getting this 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 9sm14519585pfh.160 - gsmtp
data.controller.js:
const nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'mygmail#gmail.com',
pass: 'mypass'
}
});
let mailOptions = {
from: "mygmail#example.com", // sender address
subject: "Hello ✔", // Subject line
text: "Hello This is an auto generated Email for testing from node please ignore it", // plaintext body
to: "togmail#gmail.com"
}
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});

const nodemailer = require('nodemailer');
const email = 'myemail#gmail.com';
const password = '**********';
You should set smtp host as smtp.gmail.com.
You can set smtp port number as 587 or 465.
587 is tls and 465 is ssl.
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: `${email}`,
pass: `${password}`
}
});
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
var mail = 'message';
const from_email = 'sender#email.com';
const to_email = 'receiver#email.com';
var mailOptions = {
from: email,
to: to_email,
subject: 'Your subject',
text: mail
};
}
});
I used above code, so that I sent mail.
Please try this.

Related

Sending Email using nodemailer

I am trying to send emails to using nodemailer from my site but it gives me this error
Error: Invalid login: 535-5.7.8 Username and Password not accepted.
and I made sure the password and credentials is accurate. This is my code for setting up nodemailer
function message(merchantEmail, msgTxt){
var transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
secure: true,
port: 465,
auth: {
user: 'kesterdaniel401#gmail.com',
pass: process.env.PASSWORD
},
tls: {
rejectUnauthorized: false
}
});
var mailOptions = {
from: 'kesterdaniel401#gmail.com',
to: merchantEmail,
subject: 'Sending Email using Node.js',
text: msgTxt
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
module.exports = message
This is where I called the function
message(productOwner.Email, `You have received an order from ${Buyer.Name} for the product ${product. ProductName}. Please contact the customer as soon as possible. Customer Number is ${Buyer.PhoneNumber}.`)

Nodemailer - Missing credentials for "PLAIN"

I am working with node.js and tried sending email via Nodemailer but I'm getting this error:
Missing credentials for "PLAIN"
function(token, user, done) { //sends mail
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'aimanmumtazxyz#gmail.com',
pass: process.env.GMAILPW
}
});
Any help anybody?
const nodemailer = require("nodemailer");
async function main() {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: userName, // Enter your userName or email
pass: password // Enter your password
}
});
// send mail with defined transport object
await transporter.sendMail({
from: '"Fred Foo 👻" <foo#example.com>', // sender address
to: "bar#example.com, baz#example.com", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>" // html body
}, (err, info)=>{
if (err) {
throw new Error(err)
} else {
console.log('Email sent: ' + info.response);
}
});
For more information about nodemailer, please check this link: https://nodemailer.com/about/
For sending an email by Gmail, please check this link: https://nodemailer.com/usage/using-gmail/

send email via nodemailer

I try to send email via nodemailer but getting error - TypeError: Cannot read property 'method' of undefined. It looks like sendMail function is not defined. Any advise please?
P.S. This code for chatbot hosted on AWS
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
module.exports = function someName() {
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: '7384093#gmail.com',
pass: '*******'
}
}))
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"nerd studio" <7384093#gmail.com>', // sender address
to: '7384093#gmail.com', // list of receivers
subject: 'Подтверждение запроса \\ разработак чат-ботов \\ nerd studio', // Subject line
text: 'Добрый день! Вы оставили нашему Валере запрос и мы с радостью подтверждаем его получение. В ближайшее время с вами свяжется наш менелдер', // plaintext body
html: '<b>Добрый день! Вы оставили нашему Валере запрос и мы с радостью подтверждаем его получение. В ближайшее время с вами свяжется наш менелдер</b>' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
console.log(mailOptions);
console.log(info);
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
}
You don't need to install npm nodemailer-smtp-transport, only nodemailer is enough to send email to gmail. But first, go to the https://myaccount.google.com/security google account and scroll down and check Allow less secure apps: ON and keep ON. you will send your gmail email. Here, is the full code -
var nodemailer = require('nodemailer');
app.post('/contactform', function (req, res) {
var mailOpts, smtpTrans;
//Setup Nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport(smtpTransport({
service: 'gmail',
// host:'smtp.gmail.com',
// port:465,
// secure:true,
auth: {
user: "xxxxxx#gmail.com",
pass: "xxxxxx"
}
}));
var mailoutput = "<html>\n\
<body>\n\
<table>\n\
<tr>\n\
<td>Name: </td>" + req.body.form_name + "<td></td>\n\
</tr>\n\
<tr>\n\
<td>Email: </td><td>" + req.body.form_email + "</td>\n\
</tr>\n\
<tr>\n\
<td>MN: </td>" + req.body.form_phone + "<td></td>\n\
</tr>\n\
<tr>\n\
<td>Messge: </td>" + req.body.form_message + "<td></td>\n\
</tr>\n\
</table></body></html>";
//Mail options
mailOpts = {
to: "Your_App_Name <xxxxxxxx#gmail.com>",
subject: req.body.form_subject,
html: mailoutput
};
smtpTrans.sendMail(mailOpts, function (error, res) {
if (error) {
// res.send("Email could not send due to error" +error);
return console.log(error);
}
});
console.log('Message sent successfully!');
res.render('contact.ejs');
});
//console.log(query.sql);
});
I have nodemailer currently working this way: Create a file config/mail.js:
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
host: 'yourHost',
port: 2525, //example
auth: {
user: 'yourUser',
pass: 'yourPass'
}
});
module.exports = function(params) {
this.from = 'yourEmail';
this.send = function(){
var options = {
from : this.from,
to : params.to,
subject : params.subject,
text : params.message
};
transporter.sendMail(options, function(err, suc){
err ? params.errorCallback(err) : params.successCallback(suc);
});
}
}
And then, anytime I want to send an email:
var Mail = require(path.join(__dirname, '..', '..', 'config', 'mail.js'));
var options = {
to: 'example#example.com',
subject: 'subject',
message: 'your message goes here'
}
var mail = new Mail({
to: options.to,
subject: options.subject,
message: options.message,
successCallback: function(suc) {
console.log('success');
},
errorCallback: function(err) {
console.log('error: ' + err);
}
});
mail.send();
Try this code.First you have to create an app in Google Cloud Console and Enable Gmail API from library.Get the credentials of your app.For that click on Credentials and in the place of Authorized redirect URIskeep this link https://developers.google.com/oauthplayground and save it.Next in another tab open this link https://developers.google.com/oauthplayground/ click on settings symbol on right side.And make a tick on check box(i.e,Use your own OAuth credentials) after this You have to give your clientId and clientSecret.And at the sametime on left side there is a text box with placeholder like Input Your Own Scopes there keep this link https://mail.google.com/
and click on Authorize APIs then click on Exchange authorization code for tokens then you will get your refreshToken and accessToken keep these two in your code.Hope this hepls for you.
const nodemailer=require('nodemailer');
const xoauth2=require('xoauth2');
var transporter=nodemailer.createTransport({
service:'gmail',
auth:{
type: 'OAuth2',
user:'Your_Email',
clientId:'Your_clientId',//get this from Google Cloud Console
clientSecret:'Your_clientSecret',
refreshToken:'Your_refreshToken',//get this from https://developers.google.com/oauthplayground/
accessToken:'Your_accessToken'
},
});
var mailOptions={
from:'<Your_email>',
to:'Your firends mail',
subject:'Sample mail',
text:'Hello !!!!!!!!!!!!!'
}
transporter.sendMail(mailOptions,function(err,res){
if(err){
console.log('Error');
}
else{
console.log('Email Sent');
}
})
I find solution for ,
How to send email from="userEmail" to="myEmail"?
THIS IS TRICK
var nodemailer = require('nodemailer'); router.post('/contacts-variant-2', (req, res, next) => { var name=req.body.name; var email=req.body.email; var message=req.body.message; const output=`
<h3>Contact Details</h3>
<ul>
<li>Name is : ${req.body.name}</li>
<li>Email is : ${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`; var transporter = nodemailer.createTransport({ service: 'yahoo', auth: { user: 'create_new_email#yahoo.com', pass: 'password' } }); var mailOptions = { from:'create_new_email#yahoo.com', to:'myFriend#gmail.com', subject: name, text: 'Your have a new
contact request', html:output }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log("errors is somthing "+error); res.send(404); } else { console.log('Email sent: ' + info.response); res.send(200); } }); });
Using Gmail
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Gmail
// change the user and pass !
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'myemail#gmail.com',
pass: 'myPassword'
}
});
// setup e-mail data
var mailOptions = {
from: '"Our Code World " <myemail#gmail.com>', // sender address (who sends)
to: 'mymail#mail.com, mymail2#mail.com', // list of receivers (who receives)
subject: 'Hello', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
Using Hotmail
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Outlook
// change the user and pass !
var transporter = nodemailer.createTransport({
host: "smtp-mail.outlook.com", // hostname
secureConnection: false, // TLS requires secureConnection to be false
port: 587, // port for secure SMTP
tls: {
ciphers:'SSLv3'
},
auth: {
user: 'mymail#outlook.com',
pass: 'myPassword'
}
});
// setup e-mail data, even with unicode symbols
var mailOptions = {
from: '"Our Code World " <mymail#outlook.com>', // sender address (who sends)
to: 'mymail#mail.com, mymail2#mail.com', // list of receivers (who receives)
subject: 'Hello ', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
Alternatively, if your account is hotmail instead of outlook, you can use the buil-in hotmail service using the following transport:
var transport = nodemailer.createTransport("SMTP", {
service: "hotmail",
auth: {
user: "user#hotmail.com",
pass: "password"
}
});
Using Zoho
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Gmail
// change the user and pass !
var transporter = nodemailer.createTransport({
host: 'smtp.zoho.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'myzoho#zoho.com',
pass: 'myPassword'
}
});
// setup e-mail data, even with unicode symbols
var mailOptions = {
from: '"Our Code World " <myzoho#zoho.com>', // sender address (who sends)
to: 'mymail#mail.com, mymail2#mail.com', // list of receivers (who receives)
subject: 'Hello ', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});

sending email via nodemailer not working

I have a simple piece of code which is not working as expected. I am using nodemailer.
var nodemailer = require('nodemailer');
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: 'personal gmail address',
pass: 'password'
}
});
var mailOptions = {
from: 'personal gmail address',
to: 'personal gmail address',
subject: 'Hello world!',
text: 'Plaintext message example.'
};
smtpTransport.sendMail(mailOptions, function(err) {
console.log('Message sent!');
});
I am getting the Message Sent in console. But no emails in inbox.
For gmail service I use this :
const smtpTransport = require('nodemailer-smtp-transport')
const nodemailer = require('nodemailer')
const transport = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: 'email',
pass: 'pass'
}
}))
But you need to allow less secure authentication on your gmail account or emails are not sent.
I think the steps are :
Go to : https://www.google.com/settings/security/lesssecureapps
set the Access for less secure apps setting to Enable
Found this SO: self signed certificate in certificate chain error in mail .
I needed to add this and it worked for me.
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'myemail#gmail.com',
pass: 'password'
},
tls: {
rejectUnauthorized: false
}
});
Can you check for the error message.
...
smtpTransport.sendMail(mailOptions, function(err) {
if(err)
{
console.log(err);
}
else
{
console.log('Message sent!');
}
});
Because in the sample code you had, even if the nodemailer returns valid error, it will still print Message Sent
Some times message can be queued or say any type of error in the mailOptions, the message cant be delivered.

SMTP using nodemailer in nodejs without GMail

I am using node mailer with GMail
smtpTransport = nodemailer.createTransport("SMTP", {
service: "Gmail",
auth: {
user: "myemail ",
pass: "mypass"
}
});
which is working fine, but I want to use my own email server instead of GMail.
This:
smtpTransport = nodemailer.createTransport("SMTP", {
service: "mymailservr link url",
port : 25
auth: {
user: "myemail ",
pass: "mypass"
}
});
It throws this error:
connect ECONNREFUSED
The service option is only for well-known services. To specify your own host, set host.
var smtpTransport = nodemailer.createTransport('SMTP', {
host: 'yourserver.com',
port: 25,
auth: {
user: 'username',
pass: 'password'
}
});
make sure you have the latest NodeMailer version installed
as of today (15-jan-2020) it is v6.4.2
npm install nodemailer --save
This should work:
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
host: 'smtp.server.com', // <= your smtp server here
port: 2525, // <= connection port
// secure: true, // use SSL or not
auth: {
user: 'userId', // <= smtp login user
pass: 'E73oiuoiC34lkjlkjlkjlkjA6Bok7DAD' // <= smtp login pass
}
});
let mailOptions = {
from: fromEmailAddress, // <= should be verified and accepted by service provider. ex. 'youremail#gmail.com'
to: toEmailAddress, // <= recepient email address. ex. 'friendemail#gmail.com'
subject: emailSubject, // <= email subject ex. 'Test email'
//text: emailData.text, // <= for plain text emails. ex. 'Hello world'
html: htmlTemplate // <= for html templated emails
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error.message);
}
console.log('Message sent: %s', info.messageId);
});
Hope this helps,
Thank you.
var nodemailer = require('nodemailer');
var smtpTransport = require("nodemailer-smtp-transport");
var transporter = nodemailer.createTransport(smtpTransport({
host : "example.com",
port: 25,
auth : {
user : "username",
pass : "password"
}
}));

Resources