Be the first user to complete this post

  • 0
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.
I assume that you have at least a basic understanding of nodejs and its routing. If not, take a look at this diagram that visually depicts how routing takes place in expressjs.
You probably also want to change some settings on the gmail account you want to use before proceeding.

Steps

There are just 5 steps to sending an email using nodejs
  • 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()
In the code snippets that follow, we will go through each of the above steps.
STEP 1: Install the nodemailer package.
npm install nodemailer
Once you are done with this article, you should probably learn more about nodemailer library from here. . STEP 2: Creating a transport object in your route handler.
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
        }
    });
    ...
    ...
    ...
}
STEP 3: Prepare some plaintext or HTML content to be sent in the body. I am going to simply use some text.
var text = 'Hello world from \n\n' + req.body.name;
STEP 4: Create a simple JSON object with the necessary values for sending the email.
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
};
STEP 5: Your moment of glory! - Actually send the email and handle the response.
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});
    };
});
And thats pretty much all there is to it! It was quite simple, wasn'nt it?



Also Read:

  1. Find the environment variables of a nodejs process in linux
  2. Organizing your expressjs routes in separate files.
  3. Testing promise sequence using mocha, chai, chai-as-promised, sinon
  4. Accessing the request body and session in nodejs using express
  5. Setup passportjs for local authentication and authorization using expressjs