Sending mail in node.js using nodemailer - node.js

I am trying to send mail in node.js using Nodemailer but it shows some error like
{ [Error: self signed certificate in certificate chain] code: 'ECONNECTION', command: 'CONN' }
My node.js code is
var express = require('express');
var app = express();
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport('smtps://something%40gmail.com:password#smtp.gmail.com');
var mailOptions = {
to: 'stevecameron2016#gmail.com',
subject: 'Hello ?',
text: 'Hello world ??',
html: '<b>Hello world ??</b>'
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
var server = app.listen(8900,function(){
console.log("We have started our server on port 8900");
});

try https://github.com/nodemailer/nodemailer/issues/406
add tls: { rejectUnauthorized: false } to your transporter constructor options
p.s It's not a good idea to post your mail server address, if it's a real one

To allow to send an email via “less secure apps”, go to the link and choose “Turn on”.
(More info about less secure apps)
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var mailAccountUser = '<YOUR_ACCOUNT_USER>'
var mailAccountPassword = '<YOUR_ACCOUNT_PASS>'
var fromEmailAddress = '<FROM_EMAIL>'
var toEmailAddress = 'TO_EMAIL'
var transport = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: mailAccountUser,
pass: mailAccountPassword
}
}))
var mail = {
from: fromEmailAddress,
to: toEmailAddress,
subject: "hello world!",
text: "Hello!",
html: "<b>Hello!</b><p>Click Here</p>"
}
transport.sendMail(mail, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
transport.close();
});

what #user3985565 said is correct. However , if you are using gmail you also need to change some settings in your gmail account. More specifically you need to "allow less secure apps" in you gmail account. To do that just follow these steps:
test nodemailer as it is
node will throw an error and gmail will send you a security alert email informing you that "an unsafe app tried to access your account"
in this email you need to click on "check activity" and then, in the folowing screen, you must unswer "yes"
Your next clicks in the following screens are "more information" and then "less secure apps".
finally you will see a toggle switch and you must turn it on.

i was in this trouble too, what i did is next code line:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
just before creating the smpttransport
for example, in your code just put this:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var transporter = nodemailer.createTransport('smtps://something%40gmail.com:password#smtp.gmail.com');

it worked for me.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

Related

How to make nodemailer with SMTP work?

I've already lowered my gmail account's security here:
https://myaccount.google.com/lesssecureapps
I've tried to send mail with, and without smtp, but always get some kind of error.
Error: invalid login: 535.5.....
I checked my "user", and "from" parameters are the same. Here's a bit of my code. I'm working on localhost. May it be the problem?
var nodemailer = require("nodemailer");
var smtpTransport = require("nodemailer-smtp-transport");
var transporter = nodemailer.createTransport(smtpTransport({
service: "gmail",
auth: {
user: "seratothdevelop#gmail.com", // my mail
pass: "*********"
}
}));
console.log('SMTP Configured');
var message = "<b>Kedves Felhasználó!</b>"+
"<p>Sikeresen feliratkoztál a Kutyapplikáció hírlevelére, ahonnan friss információkkal látunk el hétről-hétre.</p>"+
"<br><p>Üdvözlettel, </p><p><i>sethdevelop</i></p>";
var mailOptions = {
from: "seratothdevelop#gmail.com", // sender address
to: request.body.subscribeduser, // list of receivers
subject: "Kutyapp feliratkozás", // Subject line
html: message // You can choose to send an HTML body instead
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
}else{
console.log('Üzenet elküldve: ' + info.response);
}
transporter.close();
});

How can I create a custom smtp server to send out notification emails in Nodejs?

My requirement is to send a notification email from my application to any email id , eg: a gmail address. I went through some modules like the smtp-server ,smtp-connection and emailjs
This is what I have got till now.
var SMTPServer = require('smtp-server').SMTPServer
var server = new SMTPServer({
name: 'testDomain.com',
authOptional: true,
onAuth: function (auth, session, callback) {
callback(null, {user: 'sample-user'})
}
})
server.on('error', function (err) {
console.log('Error %s', err.message)
})
var port = 1234
server.listen(port, function () {
console.log('SERVER: Listening on port: ' + port)
var opts = {
host: '127.0.0.1',
port: port,
username: 'testUser',
password: 'testUser123',
to: 'someUser#gmail.com'
}
sendEmail(opts,function (err, message) {
server.close()
})
})
where sendEmail is a function using emailjs.
function sendEmail(opts,callback) {
var server = email.server.connect({
user: opts.username || '',
password: opts.password || '',
host: opts.host,
ssl: false
})
server.send({
text: 'i hope this works',
from: 'you <'+opts.username+'#testDomain.com>',
to: ' <'+opts.to+'>',
subject: 'testing emailjs'
}, function (err, message) {
console.log(err || message);
callback(err, message)
})
}
But it seems that the client is not able to connect to the server. It is hanging.
I tried smtp-connection like this initially:
var connection = new SMTPConnection({
port: port,
host: '127.0.0.1',
ignoreTLS: true
})
connection.connect(function () {
var envelope = {
from: opts.username+'#testDomain.com',
to: opts.to
}
var message = "Hello!!!"
connection.send(envelope, message, function(err,message){
callback(err,message)
connection.quit()
})
This seems to work but gives this output
response: '250 OK: message queued'
the smtp-connection documentation says it only queues the messages doesnt deliver it to the recipient.
How can I achieve my requirement? I am attempting to send the notification from a custom mail server because I want to avoid adding the user credentials of an email account in the code in plaintext. I am looking for a simple mailserver which can be spun up when the notification needs to be sent and then shut down.
Am I completely offtrack, not understanding how mail servers work?? Please give some feedback and a best approach to solve this.
Just my opinion but I think its better to take a separate mail server.
like the example from nodemailer:
var nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport('smtps://user%40gmail.com:pass#smtp.gmail.com');
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"Fred Foo ?" <foo#blurdybloop.com>', // sender address
to: 'bar#blurdybloop.com, baz#blurdybloop.com', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Hello world ?', // plaintext body
html: '<b>Hello world ?</b>' // 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);
});
For the security:
You can use separate file for storing the username / password.
Use can use a Token based authentication. So you don't need to save the password. An example of this is OAuth. Instead of the password you authenticate with a token. This token u get from the mailserver provider (like gmail).
An example use of oauth and nodemailer you can find here.

how to send an email in nodejs

I read the following, Sending emails in Node.js? but I'm looking for a way to send an email, not through an smtp server. As in the linux envirement you have different options such as sendmail and others
I could ofc use the environment I'm in to make use of the already existing functionality, but I would be interested to learn how one would dispatch the email using only js, if even possible..
I set up an smtp server using the smtp module: https://github.com/andris9/smtp-server why I'm interested in the delivery part of a server I already setup.
Take a look at node-mailer. You can set it up without smtp server. https://github.com/nodemailer/nodemailer
var nodemailer = require('nodemailer');
var send = require('gmail-send');
var mailserverifo = nodemailer.createTransport({
service: 'gmail',
host : "smtp.gmail.com",
port : "465",
ssl : true,
auth: {
user: 'email#gmail.com',
pass: 'password#'
}
});
var Mailinfo = {
from: 'email#gmail.com',
to: 'email#info.com',
subject: 'Testing email from node js server',
text: 'That was easy!'
};
mailserverifo.sendMail(Mailinfo, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email Send Success: ' + info.response);
}
});
Enable less secure app form setting -
https://www.google.com/settings/security/lesssecureapps
Disable Captcha -
https://accounts.google.com/b/0/displayunlockcaptcha
You can use sendmail in Node js. I'v using it and it's working fine for me.
npm install sendmail --save
const sendmail = require('sendmail')();
sendmail({
from: 'no-reply#yourdomain.com',
to: 'test#qq.com, test#sohu.com, test#163.com ',
subject: 'test sendmail',
html: 'Mail of test sendmail ',
}, function(err, reply) {
console.log(err && err.stack);
});
https://www.npmjs.com/package/sendmail
First:Install nodemailernpm install nodemailer
Then put this into your node file:
var nodemailer = require('nodemailer');
var http = require('http');
var url = require('url');
console.log("Creating Transport")
var transporter = nodemailer.createTransport({
service:'Hotmail',
auth: {
user:'salace2008765#outlook.com',
pass: 'alice123#'
}
});
var mailOptions = {
from:'salace2008765#outlook.com',
to: 'jerome20090101#gmail.com',
subject: 'This is a test: test',
text:'TgK'
}
console.log("Sending mail")
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response)
}
})
It usally works
Sources:W3Schools and Nodemailer's official site

Sending emails using Mailgun with NodeMailer package

A couple of days ago I realized that Google has changed the security of gmail accounts, particularly for the possibility of sending emails from applications. After Googling around for a while I couldn't find a fix for it.
So, I resorted to using Mailgun. I created an account and had it enabled with Business verification. However, I still can't send emails. I keep getting an error about the requested URL not being found.
I am suspecting that since I haven't set up a domain yet, it is not picking the mailgun domain it provided by default. Could someone show me how to test sending emails using Mailgun from NodeMailer indicating the sandbox name provided by mailgun.
thanks in advance
José
var nodemailer = require('nodemailer');
// send mail with password confirmation
var transporter = nodemailer.createTransport( {
service: 'Mailgun',
auth: {
user: 'postmaster#sandboxXXXXXXXXXXXXXXXX.mailgun.org',
pass: 'XXXXXXXXXXXXXXXX'
}
});
var mailOpts = {
from: 'office#yourdomain.com',
to: 'user#gmail.com',
subject: 'test subject',
text : 'test message form mailgun',
html : '<b>test message form mailgun</b>'
};
transporter.sendMail(mailOpts, function (err, response) {
if (err) {
//ret.message = "Mail error.";
} else {
//ret.message = "Mail send.";
}
});
I created the Nodemailer transport for mailgun.
Here it how it works.
You install the package with npm install as you would do with any package, then in an empty file:
var nodemailer = require('nodemailer');
var mg = require('nodemailer-mailgun-transport');
// This is your API key that you retrieve from www.mailgun.com/cp (free up to 10K monthly emails)
var auth = {
auth: {
api_key: 'key-1234123412341234',
domain: 'sandbox3249234.mailgun.org'
}
}
var nodemailerMailgun = nodemailer.createTransport(mg(auth));
nodemailerMailgun.sendMail({
from: 'myemail#example.com',
to: 'recipient#domain.com', // An array if you have multiple recipients.
subject: 'Hey you, awesome!',
text: 'Mailgun rocks, pow pow!',
}, function (err, info) {
if (err) {
console.log('Error: ' + err);
}
else {
console.log('Response: ' + info);
}
});
Replace your API key with yours and change the details and you're ready to go!
It worked me, when I added the domain also to the auth object (not only the api_key). Like this:
var auth = {
auth: {
api_key: 'key-12319312391',
domain: 'sandbox3249234.mailgun.org'
}
};

Nodemailer and GMail with access tokens

I try to use Nodemailer to send an email with my GMail account but it doesn't work, it works in local but on my remote server I recieve an email from Google "Someone is using your account...."
How can I do ?
exports.contact = function(req, res){
var name = req.body.name;
var from = req.body.from;
var message = req.body.message;
var to = '******#gmail.com';
var transport = nodemailer.createTransport("SMTP", {
service: 'Gmail',
auth: {
XOAuth2: {
user: "******#gmail.com",
clientId: "*****",
clientSecret: "******",
refreshToken: "******",
}
}
});
var options = {
from: from,
to: to,
subject: name,
text: message
}
transport.sendMail(options, function(error, response) {
if (error) {
console.log(error);
} else {
console.log(response);
}
transport.close();
});
}
Check out the solution from Unable to send email via google smtp on centos VPS:
In my case, my script is on a VPS so I don't have a way to load any url with a browser. What I did: Changed my gmail pw. Gmail > Settings > Accounts. Then in Google Accounts they listed suspicious logins that were blocked by google (these were my script's attempted logins). Then I clicked the option "Yes, that was me". After that, my script worked (using the new pw).

Resources