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.
Related
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;
I am trying to create a route that sends someone a JWT token reset link. The Route that I am having issues with is as follows:
// REQUIREMENTS
require("dotenv").config();
const express = require("express"),
expressSanitizer= require("express-sanitizer"),
router = express.Router(),
passport = require("passport"),
User = require("../models/user"),
middleware = require("../middleware"),
mailchimp = require('#mailchimp/mailchimp_marketing'),
request = require('request'),
https = require('https'),
nodemailer = require("nodemailer"),
jwt = require('jsonwebtoken');
const JWT_SECRET = "jwt_secret";
router.post('/forgot-password', (req, res, next) =>{
let userEmail = req.body.email;
let link;
User.findOne({'email': req.query.email}, function(err, username){
let userEmail = req.body.email;
if(err) {
console.log(err);
}
var message;
if(username) {
console.log(username);
message = "email exists";
console.log(message);
// SEND TOKEN HERE
const secret = JWT_SECRET + username.password;
const payload = {
id: username.id,
email: userEmail
};
let token = jwt.sign(payload, secret, {expiresIn: '15m'});
// CHECK URL PARAMS
let link = process.env.URL`/${username.id}/${token}`;
console.log(link);
console.log(payload);
return link, payload;
}
});
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
clientId: authClient,
clientSecret: authCSecret
}
});
// Email Data
let mailOptions = {
from: *****, // sender address
to: userEmail, // list of receivers
replyTo: *****,
subject: 'Reset Your Password', // Subject line
html: '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/><link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"rel="stylesheet"/><link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.0.1/mdb.min.css" rel="stylesheet"/><p class="lead">Hey, it looks like you forgot your password.</p><p class="card-text">Follow the link below to reset your password.<div class="text-center"><a class="btn btn-lg btn-primary my-3" href="'+link+'" target="_blank">click here</a></div></p><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.0.1/mdb.min.js"></script>', // html body
auth: {
user: authUser,
refreshToken: authRefreshToken,
accessToken: authAccessToken,
expires: 3599
}
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
res.send("A link has been sent to your email.");
});
});
I have confirmed the Nodemailer part works. I am just at a loss why the link is always showing as undefined when in my console it prints out a valid link to follow. All help would be appreciated!
Nodemailer is sending emails as a thread if the email has the same subject as a previously sent email. But I want to send the emails as separate emails, even if they have the same subject as each other.
I have an application that sends notification emails to users. The emails all have the same subject: notification. This is causing the emails to show as a thread, at least in Gmail:
How can I make each notification email send separately?
const nodemailer = require('nodemailer');
const logger = require('./logger');
class Email {
constructor(email, to, pass) {
this.user = email;
this.to = to;
this.pass = pass;
}
get mailOptions() {
return {
from: this.user,
to: this.to,
subject: 'notification',
html: 'You received a new purchase in your shop.',
};
}
get transporter() {
const transporter = nodemailer.createTransport({
// for zoho emails
host: 'smtp.zoho.com',
port: 587,
secure: false,
auth: {
user: this.user,
pass: this.pass,
},
});
return transporter;
}
send(cb) {
this.transporter.sendMail(
this.mailOptions,
cb ||
((error, info) => {
if (error) console.log(error);
if (info) logger.log('silly', `message sent: ${info.messageId}`);
this.transporter.close();
})
);
}
sendSync() {
return new Promise((res, rej) =>
this.transporter.sendMail(this.mailOptions, (error, info) => {
if (error) rej(error);
else res(info);
this.transporter.close();
})
);
}
}
const email = new Email(
'somesendingemail#gmail.com',
'somereceivingemail#gmail.com',
'SendINgEmAIlPassWoRD'
);
email.send();
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
I'm trying to set up nodemailer for an app. I'm receiving an error when I try it.
This is my setup:
email = setting.email;
password = setting.password;
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: '***********#gmail.com', // real email
pass: '*********' // real password
}});
// var transporter = nodemailer.createTransport({
// service: 'gmail',
// auth: {
// user: email, // Your email id
// pass: password // Your password
// }
// });
var mailOptions = {// sender address
from: email,
to: to, // list of receivers
subject: sub, // Subject line
text: text, //, /// plaintext body
html: html
}
//console.log(JSON.stringify(mailOptions));
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.error(error);
} else {
console.log(info.response);
}
;
});
});
} catch (error) {
console.error(error);
}
This is the first time I've tried using nodemailer. I am using real email and password. The error are:
(node:18974) [DEP0025] DeprecationWarning: sys is deprecated. Use util
instead. Magic happens on port 5000 ERROR! ERROR! ERROR! ERROR!
provider_analytic_daily saved. { Error: Connection timeout
at SMTPConnection._formatError (/root/faszz/node_modules/smtp-connection/lib/smtp-connection.js:528:15)
at SMTPConnection._onError (/root/faszz/node_modules/smtp-connection/lib/smtp-connection.js:514:16)
at SMTPConnection. (/root/faszz/node_modules/smtp-connection/lib/smtp-connection.js:236:14)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5) code: 'ETIMEDOUT', command: 'CONN' }
functionObj = {};
functionsObj.getSmtpTransport = function() {
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "<your email address>",
pass: "<your pass>"
}
});
return smtpTransport;
}
functionsObj.sendMailForPasswordReset = function(to, token) {
var smtpTransport = functionsObj.getSmtpTransport();
var mailOptions = {
to: to,
subject: "Blabla.com Reset Password",
html: "Hi,<br> Click to link for resetting password.<br><a href='https://<blabla.com>/reset/" + urlencode(token) + "'>Click Me !!!</a>"
}
smtpTransport.sendMail(mailOptions, function(error, response) {
if (error) {
return error;
}
else {
return true;
}
});
};
Hi,
The code above worked in my project without any error. But you should allow to third party softwares to use your google account from google.
Here the google's support page for this case:
https://support.google.com/accounts/answer/6010255?hl=en
I recommend that all input should be validated :) For example if you are taking "to" parameter from user. You should validate "to" parameter is a valid email address ?