How to Sending Email Using Express.js with Nodemailer Npm in Heroku
Since Heroku is being popular in the market, people want to set up how to send an email by using the express platform and this is the easy way and efficient way to do so. I am stepping in and present the easiest way for you all to use express.js and nodemailer (npm package)to send your email in any static website.
Expressjs Simple Setup:
let express = require("express"),
path = require('path'),
bodyParser = require('body-parser');
let app = express();
app.use(express.static('src'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.post('/send-email', function (req, res) {
// Grab the form data and send email
});
let server = app.listen(4000, function(){
let port = server.address().port;
console.log("Server started at http://localhost:%s", port);
});
Endpoint:
let express = require("express"),
path = require('path'),
nodeMailer = require('nodemailer'),
bodyParser = require('body-parser');
let app = express();
app.use(express.static('src'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.post('/send-email', function (req, res) {
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
// should be replaced with real sender's account
user: 'hello@gmail.com',
pass: 'test'
}
});
let mailOptions = {
// should be replaced with real recipient's account
to: 'info@gmail.com',
subject: req.body.subject,
text: req.body.message
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});
res.writeHead(301, { Location: 'index.html' });
res.end();
});
let server = app.listen(4000, function(){
let port = server.address().port;
console.log("Server started at http://localhost:%s", port);
});
Don’t forget to install nodemailer before you create this script above
npm i nodemailer --save--dev
Important Notes:
Remember to set IMAP access, Otherwise, you get an error.
Also, you may get another error that email working in Local but not the Heroku. Since Heroku is a virtual machine that provides your server, you need to provide access to the app and it is safe to do so.
https://accounts.google.com/b/0/DisplayUnlockCaptcha
This will allow machines to access your Gmail remotely.
Now all you need is to write a simple ajax on your website, and I will provide all that for you:
$.ajax({
url: 'your-heroku.com',
type: 'POST',
headers: {'Accept': 'application/json;'},
data: {
"subject": "subject",
"message": "some body text"
},
}).done(function (res) {
console.log(res); // it shows your email sent message.
});
That’s all you need and push your code to Heroku server.