Send an email using Nodemailer and Gmail in Node.js Express.js

Image for post
Image for post

Nodemailer

SMTP

npm install nodemailer
npm install nodemailer-smtp-transport
var nodemailer = require(‘nodemailer’);var smtpTransport = require(‘nodemailer-smtp-transport’);
var transporter = nodemailer.createTransport(smtpTransport(options))
let transporter = nodemailer.createTransport(smtpTransport({
service: ‘gmail’,
host: ‘smtp.gmail.com’,
auth: {
user: ‘user.gmail’,
pass: ‘user.password’
}
}));
const mailOptions = {
from: ‘sender.gmail’,
to: ‘receiver.email’,
subject: ‘subject’,
text: ‘message‘
};
const mailOptions = {
from: ‘sender.gmail’,
to: ‘receiver.email’,
subject: ‘subject’,
html: ‘message‘
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log(‘Email sent: ‘ + info.response);
}
});
<form role="form" action="/send-mail" method="POST">
<div class="form-group">
<label for="to">To</label>
<input type="text" class="form-control" id="to"
name="to" placeholder="Receiver Email" required>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject"
name="subject" placeholder="Subject" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message"
name="message" placeholder="Message" required></textarea>
</div>
<div class="text-center">
<button type="submit" id="submit" name="submit" class="btn
btn-primary btn-sm">Send</button>
</div>
</form>
//require
var express = require("express"),
router = express.Router(),
smtpTransport = require('nodemailer-smtp-transport');
//setup nodemailer
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
host: 'smtp.gmail.com',
auth: {
user: 'user.email',
pass: 'user.password'
}
}));
//get route to send mail, from form
router.post("/send-mail", function(req,res){
var to = req.body.to,
subject = req.body.subject,
message = req.body.message;
//options
const mailOptions = {
from: ‘example@gmail.com’,
to: to, // from req.body.to
subject: subject, //from req.body.subject
html: message //from req.body.message
}; //delivery
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
});
module.exports = router;

Undergraduate, Computer Science and Engineering, University of Moratuwa

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store