Nodemailer not working when deploying to Heroku - node.js

I am using nodemailer to send email in my server using express. Everything worked perfectly in the localhost but when I deploy it on Heroku, it does not work anymore, look like it not support nodemailer on Heroku (that is what I have researched). This is my code, would you please help me out to deal with it. Thank you so much and have a good day
This is sending single mail
exports.send_mail = (req, res, next) => {
var {subjectTo, mailList, content} = req.body;
var {attachURL} = req;
var transporter = nodemailer.createTransport({
service: 'gmail',
secure: false,
port: 465,
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD,
},
});
var mailOptions = {
from: 'sale.shopeeholic#gmail.com',
to: mailList,
cc: mailList,
subject: subjectTo,
text: `${content} \n Attached files: ${attachURL}`,
};
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log(err);
return res.status(400).json({err});
} else {
return res.status(200).json({message: `Mail sent to ${mailList}`});
}
});
};
This is sending merge mail/multiple mail
exports.merge_mail = (req, res, next) => {
console.log('merge mail begin');
const mailOptionList = req.body;
// {mails, mailContent, mailTitle}
var counter = 0;
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD,
},
});
for (var i = 0; i < mailOptionList.length; i++) {
var mailOptions = {
from: 'sale.shopeeholic#gmail.com',
to: mailOptionList[i].mails.join(','),
cc: mailOptionList[i].mails.join(','),
subject: mailOptionList[i].mailTitle,
text: mailOptionList[i].mailContent,
};
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log(err);
return res
.status(400)
.json({err, message: `trouble in sending mail at index ${i}`});
} else {
console.log(`mail sent to ${JSON.stringify(mailOptionList[i].mails)}`);
counter++;
}
});
console.log(`mail sent to ${JSON.stringify(mailOptionList[i].mails)}`);
counter++;
console.log(counter);
}
if (counter === mailOptionList.length) {
return res.status(200).json({message: 'mail sent all'});
}

Probably process.env.EMAIL and process.env.PASSWORD are undefined. You have to set env variables in Heroku. Here's how:
https://devcenter.heroku.com/articles/config-vars

Related

response: '535-5.7.8 Username and Password not accepted. Learn more at\n'

My Node js code is sending proper email on localhost but in backend there showing email and password not valid ?
const nodemailer = require("nodemailer");
const sendEmail = async (subject, message, send_to, sent_from, reply_to) => {
// Create Email Transporter
const transporter = nodemailer.createTransport({
host: process.env.EMAIL_HOST,
port: 465,
secure: true,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
// Options for sending email
const options = {
from: sent_from,
to: send_to,
reply_to: reply_to,
subject: subject,
html: message,
};
// Check email sent successfully or not
transporter.sendMail(options, function (err, info) {
if (err) {
console.log(err);
} else {
console.log(info);
}
});
};
module.exports = sendEmail;

not sure why nodemailer isnt working properly

Not sure why this isnt working properly. i think the configuration looks right but I keep getting this error :getaddrinfo ENOTFOUND smpt.mydomian.com
let transporter = nodemailer.createTransport({
host: "smtp.mydomain.com",
port: 465,
secure: true,
auth: {
user: "abc#mydomain.com",
pass: "password",
},
});
let mailOptions = {
from: email,
to: "abc#domail.com",
subject: `New Lead ${fullName}`,
text: newMail,
};
// step 3
transporter.sendMail(mailOptions, (err, data) => {
if (err) {
console.log("there is an error " + err);
} else {
console.log("mail sent successfully");
}
});
});
in my opinion its better to create a class for that just like this
class Mailer {
sendMail = async (emailAddress) => {
let transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: testUser,
pass: testPass,
},
});
const option = {
from: `${EMAIL_ADDRESS}`,
to: emailAddress,
subject: "test Subject",
text: "Test text",
};
await transporter.sendMail(option, (err, info) => {
if (!err) {
console.log(`Email sent Successfully ... !`.green.underline.bold);
return true;
} else {
console.log(
`We have problem while sendil Email ... !`.red.underline.bold
);
return false;
}
});
};
}
i hope this class help you

Nodemailer: set configuration to send email from custom email

I am using Nodemailer to send emails to my users.
Email used to send emails is 'xyz#toyjunction.online' not gmail.
const nodemailer = require('nodemailer');
let sendMail = async (userName, email, password) => {
return new Promise(function (resolve, reject) {
var smtpConfig = {
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'xyz#toyjunciton.online',
pass:'xxxxxx'
}
};
var transporter = nodemailer.createTransport(smtpConfig);
const mailOptions = {
from: 'xyz#toyjunciton.online',
to: email,
subject: 'Demo Subject',
html: `Hi ${userName}, Your new password is ${password}.`
};
transporter.sendMail(mailOptions, (err, info) => {
let rtnStatus;
if (err) {
reject(false);
} else {
resolve(true);
}
return rtnStatus;
});
});
}
module.exports = sendMail;
Getting error:
Invalid login: 535-5.7.8 Username and Password not accepted.
I have seen a lot of solutions on the internet but not worked for me.

Nodemailer returns nothing on sending mail

I'm using nodemailer to try and get an admin to send an email, but the code I have so far returns no info or error.
The promise returns with no issue, but it's always empty.
Trying to use transporter.verify returns no info or error as well.
There are no issues with finding the admin in question.
var deferred = Q.defer();
Admin.findOne({username: 'admin'}, function(err, res)
{
if(err) deferred.resolve(err);
if(res)
{
var admin = _.omit(res.toJSON(), 'password');
var transporter = nodemailer.createTransport("SMTP", {
service: 'gmail',
auth: {
user: 'sender#gmail.com',
pass: "password_here"
}
});
var mailOptions = {
from: 'sender#gmail.com',
to: 'destination#hotmail.com',
subject: 'TEST',
text: 'TEST',
html: '<p> TEST EMAIL </p>'
};
transporter.sendMail(mailOptions, function (err, info) {
if (err) deferred.reject(err);
if(info){
deferred.resolve(info);
} else {
deferred.resolve();
}
});
} else {
deferred.reject("Cannot find admin");
}
});
return deferred.promise;
Please edit the code, it looks like you have an error on mongo with 'Admin.findOne'
if(err) deferred.resolve(err);
to
if(err) deferred.reject(err);

How do I get nodemailer to work?

I cannot figure out how to get nodemailer to work, I have inserted my credentials for gmail too and tried sending an email to myself but it did not send me anything and it did not err, so I am confused. It is possible that I am missing stuff from my code...
here is the email file:
var nodemailer = require('nodemailer');
var config = require('./config/config');
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: config.mailer.auth.user,
pass: config.mailer.auth.pass
}
});
var EmailAddressRequiredError = new Error('email address required');
exports.sendOne = function(templateName, locals, fn) {
if(!locals.email) {
return fn(EmailAddressRequiredError);
}
if(!locals.subject) {
return fn(EmailAddressRequiredError);
}
// template
var transport = smtpTransport;
transport.sendMail({
from: config.mailer.defaultFromAddress,
to: locals.email,
subject: locals.subject,
html: html,
text: text
}, function (err, responseStatus) {
if(err) {
return fn(err);
}
return fn(null, responseStatus.message, html, text);
});
};
Here is the route file sending the email:
exports.forgotPasswordPost = function(req, res, next) {
console.log("Forgot Password Post");
if(req.body.email === '') {
console.log('err');
} else {
crypto.randomBytes(48, function(ex, buf) {
var userToken = buf.toString('hex');
console.log(userToken);
User.findOne({email: (req.body.email)}, function(err, usr) {
if(err || !usr) {
res.send('That email does not exist.');
} else {
console.log(usr);
//just call the usr found and set one of the fields to what you want it to be then save it and it will update accordingly
usr.token = userToken;
usr.tokenCreated = new Date ();
usr.save(function(err, usr){
// res.redirect('login', {title: 'Weblio', message: 'Your token was sent by email. Please enter it on the form below.'});
console.log(usr);
});
console.log(usr);
var resetUrl = req.protocol + '://' + req.host + '/password_reset/' + usr.token;
console.log(resetUrl);
var locals = {
resetUrl: resetUrl,
};
console.log(locals);
mailer.sendOne('password_reset', locals, function(err, email) {
console.log('email sent');
res.redirect('successPost');
});
}
});
});
}
};
Do I need anything else beside what I have here?
I did not identify the locals correctly.
This is the code that worked for me:
var nodemailer = require('nodemailer');
var config = require('./config/config');
var smtpTransport = nodemailer.createTransport("SMTP",{
// host: "smtp.gmail.com",
// secureConnection: true,
// port: 465,
service: "Gmail",
//debug : true,
auth: {
user: config.mailer.auth.user,
pass: config.mailer.auth.pass
}
});
var EmailAddressRequiredError = new Error('email address required');
exports.sendOne = function(template, locals, err) {
var message = {
from: config.mailer.defaultFromAddress,
to: locals.email,
subject: locals.subject,
html: locals.html,
text: locals.text
};
console.log('hitlocal email');
console.log(message);
//console.log(message.to.locals.email);
if(!locals.email) {
// console.log('email err');
}
if(!locals.subject) {
console.log('subj err');
}
// template
var transport = smtpTransport;
// console.log('hit here');
// console.log(transport);
transport.sendMail(message, function(err) {
if(err) {
console.log('email js error');
console.log(err);
}
console.log('Message sent')
//return fn(null, responseStatus.message, html, text);
});
};
And this is the routes file:
var locals = {
email: 'first last <' + req.body.email + '>',
subject: 'Password Reset',
html: '<p> Please go to the following link to reset your password.' + resetUrl + '</p>',
text: 'Texty Text it'
};
console.log('locals spot here');
console.log(locals.email);
mailer.sendOne('forgotPassword', locals, function(err) {
console.log('email sent');
});
I think you need to point to the gmail server not Gmail. I forget what it is exactly but sometihng like gmail.smtp

Resources