Nodemailer not able to create transport / 502 error - node.js

I am having contiunual woes with getting nodemailer to send. I have now found the lowest security email account I can to see if I can get the thing working with a view to increasing security once something is getting through. My code is:
app.post("/contact-us", function(req, res){
var mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport({
host: 'smtp.123-reg.co.uk',
port: 25,
secure: false, // upgrade later with STARTTLS
auth: {
user: 'enquiries#*********.co.uk',
pass: '**********'
}
});
mailOpts = {
from: "enquiries#*******.co.uk",
to: "**********#mac.com",
subject: 'Website contact form',
text: "test email"
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
console.log(error);
res.render('contact', { title: '********', msg: 'Error occured, message not sent.', err: true, page: 'contact-us' });
}
//Yay!! Email sent
else {
console.log("message sent");
res.render('/');
}
});
});
Neither of the console.logs are coming back, instead the request is met with a timeout & 502 message,
Thanks

Just in case anyone searches for this in the future; the problem was within cloud 9 which wouldn't allow access to the email account to prevent spam.

Related

Error using NodeMailer on Node.js server to generate emails - '451 4.7.0 Temporary server error. PRX4'

I use a Microsoft 365 Outlook account hosted on GoDaddy.
I am attempting to have my Node server send an email to my Outlook account when user clicks the [contact us] button. The code is below:
const nodemailer = require('nodemailer');
app.post('/contact', function(req, res){
res.send(JSON.stringify(req.body));
//generate email
let transporter = nodemailer.createTransport({
host: 'smtp.office365.com',
port: 587,
secure: false,
auth: {
user: 'myemail#mysite.com',
pass: 'mypass'
}
});
const mailOptions = {
from: '"Administrator" <myemail#mysite.com>',
to: 'myemail#mysite.com',
subject: "Someone has messaged your website",
html: "<p>Name: " + req.body.fullName + "<br>Email: " + req.body.email + "<br>Message: " + req.body.msg + "</p>"
};
transporter.sendMail(mailOptions, function (err, info) {
if(err)
console.log(err)
else
console.log(info.messageId);
});
});
The error that is being logged to console is:
'451 4.7.0 Temporary server error. Please try again later. PRX4 [CO2PR04CA0181.namprd04.prod.outlook.com]'
UPDATED 7/13
Another error message which may be more useful (as is first line in error stack) is the following:
at SMTPConnection._formatError
I am using this function to send mail to outlook, try and see if it works.
The only missing thing I can suspect is tls.
module.exports.sendEmail = function (options) {
if(!options){
throw new Error("invalid options");
} else if(!options.auth) {
throw new Error("missing user and pass");
}
var transporter = nodemailer.createTransport({
host: 'smtp.office365.com', // Office 365 server
port: 587, // secure SMTP
secure:false, // false for TLS -
auth: options.auth,
tls: {ciphers: 'SSLv3'} // <<< try adding it
});
transporter.sendMail({
from: options.from,
sender: options.sender,
replyTo: options.replyTo,
to: options.to,
subject: options.subject,
cc:options.cc,
bcc:options.bcc,
text:options.text,
html:options.html,
attachments:options.attachments,
}, function (err, info) {
if (err && options.onError) {
options.onError(err);
}
else if(options.onSuccess) {
options.onSuccess(info);
}
});
}
****** caller ******
nodeoutlook.sendEmail({
auth: {
user: "user#outlook.com",
pass: "********"
},
from: 'from#outlook.com',
to: 'to#gmail.com',
subject: 'subject',
html: '<b>html</b>',
text: 'text',
replyTo: 'replyTo#gmail.com',
attachments: [],
onError: (e) => console.log(e),
onSuccess: (i) => console.log(i)
}
Understand this is a pretty lame answer....but its the truth!!
Im changed the password (mypass) for my email account then it worked.

E-mail getting rejected sent by Nodemailer

I am trying to send an email which includes HTML content with the help of nodemailer-express-handlebars. Every time my mail gets blocked by the Gmail which can be checked in sender's Gmail sent-box whereas I got success msg from nodemailer
Email sent: 250 2.0.0 OK 1595608108 i66sm6757247pfc.12 - gsmtp
I am unable to understand why this happening as when I send a mail with text, it gets delivered.
NODEMAILER CODE
sendMail=(email)=>{
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'emailId',
pass: 'password'
}
});
transporter.use('compile',hbs({
viewEngine:{
partialsDir:"./views/",
defaultLayout: "",
layoutsDir: "",
},
viewPath:"./views/",
extName:'.hbs',
}))
var mailOptions = {
from: '<xyz#gmail.com>',
to: email,
subject: 'Your order has been placed successfully.',
template:'mail',
context:{
name:"XYZ",
address:"133"
}
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
It's recommended to use OAuth2 with NodeMailer and Gmail. Using the plain username and password might be what's causing you problems.

Nodemailer "connect ETIMEDOUT" with custom domain

I'm making a forgot password backend route in Node.js and I'm attempting to use nodemailer to send the email from a custom domain I purchased from namecheap.com, along with the email domain. I'm not sure if it's a problem with the host, the port/security, or the auth. However, when I change the host it gives a a ECONREFUSED error instead so I believe that part is working. My firewall is (as far as I can tell) disabled and I restarted, however it is harder to tell because Norton Antivirus controls it.
This is my code, taken from a router.get route in my back-end.
The full error is "connect ETIMEDOUT" then an ip address with :587 at the end.
const transporter = createTransport({
host: 'axotl.com',
port: 587,
secure: false,
auth: {
user: config.get('emailUser'),
pass: config.get('emailPass')
}
});
let resetLink = '';
let authToken = '';
await jwt.sign({ email: req.params.email }, config.get('JWTSecret'), { expiresIn: 10800000 }, (err, token) => {
if (err) throw err;
authToken += token;
})
resetLink = await `${config.get('productionLink')}/recipients/resetpassword/${authToken}`
console.log(`resetlink : ${resetLink}`)
const mailOptions = {
from: '"Axotl Support" <support#axotl.com>',
to: req.params.email,
subject: "Forgot Password",
text: `Hello ${req.name},\n\nHere is the password reset link you requested (expires in 3 hours): ${resetLink}\nIf you did not request this, please notify us at http://axotl.com/support\n\nThanks!\n-Axotl Support`
}
try {
console.log('trycatch entered')
// const verified = await transporter.verify()
// console.log(`verified : ${verified}`)
const res = await transporter.sendMail(mailOptions)
console.log('email completed')
console.log(res)
res.json({ msg: "email sent" })
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error")
}
Turns out I was using the wrong host domain-- the service doesn't directly host the email domain on the website. I don't know enough about this specific section. I changed it to the email host and it worked.

nodemailer not sending mail, giving 250 ok

I've been at this problem all afternoon, all ideas are welcome.
I'm currently running the following example code to locate the issue:
router.get('/', function(req, res, next) {
let transporter = nodemailer.createTransport({
host: "cpsrv14.misshosting.com",
port: 587,
secure: false,
auth: {
user: config.email.user,
pass: process.env.EMAIL_PASS
},
tls: {
rejectUnauthorized: false
}
});
// verify connection configuration
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages");
}
});
transporter.sendMail({
from: '"Fred Foo 👻" <foo#example.com>', // sender address
to: 'christopher.rosenvall#gmail.com', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Hello world?', // plain text body
html: '<b>Hello world?</b>' // html body
}).then(resp => {
console.log('Message sent: %s', JSON.stringify(resp));
res.status(200).json({
success: true
})
}).catch( err => {
console.log(err);
res.status(400)
});
});
On request console gives me the following which seems ok to me:
Server is ready to take our messages
Message sent: {"accepted":["christopher.rosenvall#gmail.com"],"rejected":
[],"envelopeTime":84,"messageTime":403,"messageSize":603,"response":"250 OK id=1iFhm4-0004WG-
NM","envelope":{"from":"foo#example.com","to":["christopher.rosenvall#gmail.com"]},"messageId":"
<7f8f8aab-f900-1e8e-2cde-3da5ad2687ba#example.com>"}
GET / 200 762.254 ms - 16
I've tried messing around with running secure and not, with the tls setting and without - doesn't seem to make a difference as long as I can authenticate.
Problem is that the email is never sent, ive tried sending it to a bunch of different email addresses and not a single one has recieved the email.
I reinstalled the project and now everything is working, odd.
Double-check if you give from in your option. I faced this problem. in my case, I didn't provide from in the option field. But everything is working after being given from:fromemail#mail.com

Nodemailer fails on live server but works on local machine

Using nodemailer to send a registration confirmation email. Works fine on my local machine, but fails from live server (using DigitalOcean droplet & InMotionHosting email account).
I have tried as many things as I can think of to no avail, so I don't know what to do next. Any help is appreciated.
Here's the code:
let transporter = nodemailer.createTransport({
host: 'mail.domain.com',
port: 587,
secure: false,
auth: {
user: 'test#domain.com',
pass: '654cba'
},
// true for live server, false for local machine
tls: {
rejectUnauthorized: true
}
});
let mailOptions = {
from: '"Register" <test#domain.com>',
to: user.username, // email address from user object
subject: 'Registration',
html: '<h1>mail content</h1>'
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
return res.send('Error sending confirmation email to: ' + user.username);
}
console.log('Message sent: %s', info.messageId);
req.flash('success', 'Success! Welcome ' + user.fullname + '! Please check your email, and click the link to complete your registration.');
res.redirect('/');
});
I set the tls.rejectUnauthorized to 'false' for the local machine and it works as expected.
On the live server, I set it to 'true', but receive the error message ('Error sending confirmation email to: ' + user.username) after transporter.sendMail() is executed. I tried eliminating this among many other tests to no avail.
Thank you for any assistance.

Resources