Be the first user to complete this post
|
Add to List |
Send email using nodejs and express in 5 simple steps
Sending automatic emails is a very common task and doing so in nodejs is pretty straigtforward as well. In this article, I will demonstrate a simple example of sending emails using nodejs in 5 simple steps.
This article is written around the following scenario in mind
- You have an email account with an email provider like Google which you want to specify as the 'sender'. There is a simple reasoning behind doing so. Emails are sent from one server to another and in order to avoid landing your email in the recipient's spam folder, you want to use a truster server as the sender of the email aka - Google's mail servers. For the purpose of this article, we will assume this email address is
[email protected]
. - You have a web page that has a contact form where a user enters some information and clicks on submit. Upon clicking submit your express server needs to capture this data and send the request information to another email address.
You probably also want to change some settings on the gmail account you want to use before proceeding.
There are just 5 steps to sending an email using nodejs Steps
- Install the nodemailer package.
- Create a transport object using nodemailer.createTransport() and pass it your email credentials.
- Prepare the message to be sent in the body.
- Create an object with information about the sender, email subject, recipient and the body content that we prepared earlier.
- Send the email using - transporter.sendMail()
STEP 1: Install the nodemailer package.
npm install nodemailer
var nodemailer = require('nodemailer');
var router = express.Router();
app.use('/sayHello', router);
router.post('/', handleSayHello); // handle the route at yourdomain.com/sayHello
function handleSayHello(req, res) {
// Not the movie transporter!
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: '[email protected]', // Your email id
pass: 'password' // Your password
}
});
...
...
...
}
var text = 'Hello world from \n\n' + req.body.name;
var mailOptions = {
from: '[email protected]>', // sender address
to: '[email protected]', // list of receivers
subject: 'Email Example', // Subject line
text: text //, // plaintext body
// html: '<b>Hello world ✔</b>' // You can choose to send an HTML body instead
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
res.json({yo: 'error'});
}else{
console.log('Message sent: ' + info.response);
res.json({yo: info.response});
};
});
Also Read:
- Setup passportjs for local authentication and authorization using expressjs
- Installing, Listing and Uninstalling packages using npm
- Error: can not find module 'underscore'
- gzip compress and cache api response in express
- Find the environment variables of a nodejs process in linux