Sending emails using Mailgun with NodeMailer package - node.js

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'
}
};

Related

MailGun results in 401 forbidden using nodeJs

I am trying to send an email using mailgun and nodejs.
I took the code MailGun provides you and added my domain name and api key:
const mailgun = require('mailgun-js');
const DOMAIN = 'mail.mywebsite.com';
const mg = mailgun({apiKey: "this-is-myApiKey", domain: DOMAIN});
const data = {
from: 'Support <support#mywebsite.com>',
to: 'myemail#gmail.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mg.messages().send(data, function (error, body) {
console.log(1, error);
console.log(2, body);
});
This results in a 401 forbidden, but if I change to my sandbox domain name, then it works. Does anyone have some helpful tips to fix this?
mail.mywebsite.com = domain name set under sending domains
this-is-myApiKey = my private api key found here: https://app.mailgun.com/app/account/security/api_keys
It could be due to incorrect domain name of mailgun. Make sure that you are using the correct apikey and domain name.
Might your Domain Name issue.
const mailgun = require("mailgun-js")({
apiKey: 'your_api_key',
domain: 'mg.yourDomainName.com'
});
const data = {
from: "no-reply#yourDomainName.com",
to: 'abcd#gmail.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomeness!'
};
mailgun.messages().send(data, (error, body) => {
console.log(body);
if(!error)
res.status(200).json({
message:"mail sent"
})
});
That's because in new mailgun api v3 you have to follow a different approach:
See my sample code below its working:
var formData = require('form-data');
const Mailgun = require('mailgun.js');
const mailgun = new Mailgun(formData);
const mg = mailgun.client({
username: 'api',
key: process.env.EMAIL_MAILGUN_API_KEY
});
mg.messages.create(process.env.EMAIL_MAILGUN_HOST, {
from: "sender na,e <"+process.env.EMAIL_FROM+">",
to: ["dan#dominic.com"],
subject: "Verify Your Email",
text: "Testing some Mailgun awesomness!",
html: "<h1>"+req+"</h1>"
})
.then(msg => {
console.log(msg);
res.send(msg);
}) // logs response data
.catch(err => {
console.log(err);
res.send(err);
}); // logs any error
make sure to utilize the DNS name you verified. i was trying to use my domain name (as everything in their documentation seems to dictate) and repeatedly faced HTTP 401 errors. as soon as i changed DOMAIN_NAME to VERIFIED_DNS_NAME it worked.
e.g., my domain was blahblah.com. however, the DNS name i verified was mg.blahblah.com. when i changed my client to utilize that verified DNS name, it all worked

MERN Stack Email Confirmation

I've been scouring the internet on how to implement Nodemailer into a MERN stack application to send an email confirmation on user login.
I've got the application setup and properly logging in / logging out users and having them authenticated through that process. However, the implementation of nodemailer, jwt tokens and the front end of react.
I've not been able to find a way to implement this into my application and am asking for any recommendations or for a point in the right direction to learn this particular functionality.
Here's the link to the github repo for a look at the code: https://github.com/sethgspivey/mern-stack-two.git
I've got the initial test code for Nodemailer to work from the index.js file in the root directory. But again, the implementation into the react front end is where I'm hung up.
I did something similar in a project I built first you need to build out an endpoint that will be hit when the login is accepted something along the lines of:
const router = require("express").Router()
const mailer = require('../controllers/mailerController')
router
.route('/your-end-point-here')
.post(mailer.addToMailList)
module.exports = router
Notice this uses a controller that I built out. The controller will look something similar to this:
const nodemailer = require('nodemailer')
module.exports =
{
addToMailList: function (req, res)
{
let { newUser } = req.body
let transporter = nodemailer.createTransport({
service:'gmail',
auth: {
user: 'yourcompanyemail#gmail.com',
pass: 'somepassword'
}
});
message = "You just logged in!"
// setup email data with unicode symbols
let mailOptions = {
from: '"Your Company Name" <yourcompanyemail#gmail.com>', // sender address
to: newUser, // list of receivers
subject: "Welcome Letter", // Subject line
text: message // plain text body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return
console.log(error);
}
res.json(info);
});
}
}
// email data with unicode
let mailOption = {
from: '"" yourcompanyemail#gmail.com',
to: #mail,
subject: "hello ",
text: MyMessage
};

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 mail in node.js using nodemailer

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";

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