Cannot send email in nodejs using nodemailer - javascript

I used nodemailer and my code as follows:
const nodemailer = require('nodemailer');
module.exports = function(obj) {
return new Promise((resolve, reject) => {
console.log('In root to mail send file...');
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'myemail#gmail.com',
pass: 'my password'
}
});
let mailOptions = {
from: '<myemail#gmail.com>', // sender address
to: obj.email, // list of receivers
subject: obj.subject, // Subject line
text: obj.msg, // plain text body
html: obj.html_msg // html body
};
console.log('sending function');
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log('Error due to send mail' + error);
reject(error);
} else {
console.log('Message %s sent: %s', info.messageId, info.response);
resolve(info);
}
});
});
}
When I run the code, I got this error
{
Error: connect ETIMEDOUT 74.125.200.109:465 at
Object.exports._errnoException (util.js:1022:11) at
exports._exceptionWithHostPort (util.js:1045:20 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
code: 'ECONNECTION',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '74.125.200.109',
port: 465,
command: 'CONN'
}
I don't know why, please help me if anybody know why this error occurred.
I have already set Access for less secure apps: turn on in my gmail account.

You could be behind a network proxy which could be causing a timeout error.

Related

Sending gmail using nodemailer but Connection Timeout Error

I'm trying to send gmail using nodemailer.
Here is my code.
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '<sender#gmail.com>',
pass: '<password>'
}
});
var mailOptions = {
from: '<sender#gmail.com>',
to: '<receiver#gmail.com>',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
But I always got this error.
{ Error: Connection timeout
at SMTPConnection._formatError (E:\Work\Web\GatherSense\gather-sense-backend\node_modules\nodemailer\lib\smtp-connection\index.js:771:19)
at SMTPConnection._onError (E:\Work\Web\GatherSense\gather-sense-backend\node_modules\nodemailer\lib\smtp-connection\index.js:757:20)
at Timeout._connectionTimeout.setTimeout (E:\Work\Web\GatherSense\gather-sense-backend\node_modules\nodemailer\lib\smtp-connection\index.js:229:22)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10) code: 'ETIMEDOUT', command: 'CONN' }
I've spent much time and tried in many ways such as allowing secure less apps and turning off firewalls.
But always get the same error. Please help me and thank you.
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
import config from '../config/environment';
const transporter = nodemailer.createTransport(smtpTransport({
host: config.email_config.SMTP_HOST,
port: config.email_config.SMTP_PORT,
tls: {
rejectUnauthorized: false
},
auth: {
user: config.email_config.SMTP_AUTH_USER,
pass: config.email_config.SMTP_AUTH_PASS
}
}));
export function mail(emailObj) {
return new Promise((resolve, reject) => {
transporter.sendMail(emailObj)
.then(success => {
if (success) {
console.log("Email success:::", success);
resolve();
} else {
resolve(null);
}
}).catch(err => {
console.log("Email Error:::", err);
reject(err)
})
})
}

Nodemailer was sending mails but then it suddenly stopped, now it's giving me this error

This worked like some days ago but then it stopped. I really don't know what's going on. PS: I am on a Mac and it does not look like it's a firewall issue.
exports.sendEmail = (recipient, subject) => {
const mailTransporter = nodeMailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS
}
})
const mailOptions = {
from: process.env.EMAIL_USER,
to: recipient,
subject,
html: htmlTemplate(generatePasswordResetLink(),recipient),
}
return mailTransporter.sendMail(mailOptions, (error, success) => {
if (error) {
console.log(error);
return error;
}
return success;
})
The console.log(error); in the code spits this
{ Error: connect ECONNREFUSED 74.125.133.109:465
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
errno: 'ECONNREFUSED',
code: 'ESOCKET',
syscall: 'connect',
address: '74.125.133.109',
port: 465,
command: 'CONN' }
And I have tried like everything possible to get it to work. I have also restarted my laptop.
PS:
user: 'a valid gmail account',
pass: 'correct pass for the account'

JavaScript AWS Cognito Connection Problems "NetworkError"

I'm running into a strange problem with AWS Cognito. I'm able to create user accounts, however when I attempt to set the created user to a group it is
giving me a network timed out error.
Setup:
const AmazonCognitoIdentity = require('amazon-cognito-identity-js')
const AWS = require('aws-sdk')
const CognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider({
region: 'us-east-1 ', // 100% sure this is the correct region
apiVersion: '2016-04-18'
})
const UserPoolId = config.cognito.userPoolId
const ClientId = config.cognito.clientId
const userPool = new AmazonCognitoIdentity.CognitoUserPool({ UserPoolId, ClientId })
Creating account:
userPool.signUp(email, password, [ emailAttribute ], null, (err, data) => {
if(err) {
console.error(err)
return res.redirect('/signup')
}
CognitoIdentityServiceProvider.adminAddUserToGroup({
GroupName: 'TRIAL',
UserPoolId,
Username: email
}, (err, data) => {
if(err) {
console.error(err)
return res.redirect('/signup')
}
res.redirect('/dashboard')
})
})
The account gets made correctly, however when attempting to add the new account to a group I get this error:
{ Error: connect ETIMEDOUT 104.239.207.44:443
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
message: 'connect ETIMEDOUT 104.239.207.44:443',
code: 'NetworkingError',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '104.239.207.44',
port: 443,
region: 'us-east-1 ',
hostname: 'cognito-idp.us-east-1',
retryable: true,
time: 2018-06-20T14:01:49.029Z }
I find this very strange as I just was able to create an account successfully.
Any ideas on why this is happening?
Thanks

Mailing with Node.js. Issue with the host property

I know there are many posts like this here, but I couldn't find any information that would solve my issue. So I tried using both nodemailer and emailjs.
I have this code:
This is for nodemailer
var nodemailer = require('nodemailer');
nodemailer.createTestAccount((err, account) => {
if (err) console.log(err);
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport({
host: "smtp.Hotmail.com", // Just Hotmail doesn't work either
// port: 587,
auth: {
user: 'xxx#outlook.com',
pass: 'xxx'
}
});
// setup email data with unicode symbols
let mailOptions = {
from: `${req.body.fullName} ${req.body.email}`, // sender address
to: 'alexander.ironside#mygeorgian.ca', // list of receivers
subject: 'Email from SMWDB contact form', // Subject line
html: `<h4>Name: ${req.body.fullName}</h4>
<h4>Company: ${req.body.company}</h4>
<h4>Phone: ${req.body.phone}</h4>
<p>Message: ${req.body.message}</p>`
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
});
});
And this for emailjs
var email = require("emailjs");
var server = email.server.connect({
user: "xxx#outlook.com",
password: "xxx",
host: "smtp-mail.outlook.com",
tls: {ciphers: "SSLv3"}
});
var message = {
text: `Test`,
from: `${req.body.fullName} <${req.body.email}>`,
to: `Alex <alexander.ironside#mygeorgian.ca>`, // list of receivers
// cc: "else <else#your-email.com>",
subject: 'Email from SMWDB contact form', // Subject line
attachment:
[
{
data: `
<h4>Name: ${req.body.fullName}</h4>
<h4>Company: ${req.body.company}</h4>
<h4>Phone: ${req.body.phone}</h4>
<p>Message: ${req.body.message}</p>`
, alternative: true
},
]
};
// send the message and get a callback with an error or details of the message that was sent
server.send(message, (err, message) => {
console.log(err || message);
});
The problem I think is that as host both docs say something like this: smtp.your-email.com, meanwhile all code examples say this: host: "Hotmail". What's the correct way?
I don't really care which package I'm using.
I have to use Hotmail/Yahoo and cannot use Gmail (Too many accounts activated with one phone number)
Now to the errors:
Emailjs throws this:
{ Error: bad response on command '
.': 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message. and then there is a lot of numbers and a callback trace.
Nodemailer throws this:
{ Error: getaddrinfo ENOTFOUND smtp.Hotmail.com smtp.Hotmail.com:587
at errnoException (dns.js:50:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
code: 'ECONNECTION',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'smtp.Hotmail.com',
host: 'smtp.Hotmail.com',
port: 587,
command: 'CONN' }
I used to do this in PHP and have no idea why it's so complicated with Node, but I guess there must be a reason.
I asked a friend to create a Gmail account and it worked right away. If you hit the same problem, don't bother with anything else. Just use Google.
That's the transporter code that worked for me
var transporter = nodemailer.createTransport({
host: "smtp.gmail.com", // hostname
auth: {
user: 'xxx#gmail.com',
pass: 'xxx'
}
});

nodemailer google smtp connection closed error

I am trying to send email using nodemailer and nodemailer-smtp-transport in express js. i am creating a custom module to send mails to the user. When ever i am executing the script it is throwing 2 specific errors.
Error 1
D:\Projects\project_name\modules\mailer.js:45
throw error;
^
Error: Connection closed
at SMTPConnection.<anonymous> (D:\Projects\WISSENX\node_modules\nodemailer-smtp-transport\lib\smtp-transport.js:113:29)
at SMTPConnection.g (events.js:260:16)
at emitNone (events.js:67:13)
at SMTPConnection.emit (events.js:166:7)
at SMTPConnection._destroy (D:\Projects\WISSENX\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\lib\smtp-connection.js:558:10)
at SMTPConnection._onEnd (D:\Projects\WISSENX\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\lib\smtp-connection.js:538:10)
at Socket.g (events.js:260:16)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:921:12)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)
Error 2
{
[Error: getaddrinfo ENOTFOUND smtp.gmail.com smtp.gmail.com:465]
code: 'ECONNECTION',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'smtp.gmail.com',
host: 'smtp.gmail.com',
port: '465',
command: 'CONN' }
My Complete code is
var nodemailer = require('nodemailer');
var smtpTransport = require("nodemailer-smtp-transport")
var constants = require('./../modules/constants');
/*var smtpTransport = nodemailer.createTransport(constants.MAIL_HOST,{
service : "Gmail",
auth: {
user: constants.MAIL_FROM_AUTH,
pass: constants.MAIL_PASSWORD
}
});*/
var smtpTransport = nodemailer.createTransport(smtpTransport({
host : constants.MAIL_HOST,
secureConnection : constants.MAIL_SECURE,
port: constants.MAIL_PORT,
auth : {
user : constants.MAIL_FROM_AUTH,
pass : constants.MAIL_PASSWORD
},
ignoreTLS: true
}));
var sendMail = function(req, res, template, to, subject, callback) {
var mailOptions = {
from: constants.MAIL_FROM, // sender address
to: to, // list of receivers
subject: subject, // Subject line
text: "random text", // plaintext body
html: template // html body
}
console.log(mailOptions);
console.log(smtpTransport);
// send mail with defined transport object
smtpTransport.sendMail(mailOptions, function(error, response){
console.log("Message sent: " + response);
console.log(error);
if(error) {
throw error;
console.log(error);
}
else {
console.log("Message sent: " + response.message);
}
smtpTransport.close(); // shut down the connection pool, no more messages
});
}
exports.sendMail = sendMail;

Categories

Resources