How to Send Email Using Nodejs and Mandrill

In previous tutorial, we have learned how to design and develop a fully fledged email verification system using Node.js and Redis. We have used Mandrill over there to send an Email.

In this post, we are going to learn how to create a Mandrill account and get an API key.

Let’s begin.

Create MailChimp account

Mandrill is the product of Mailchimp. You need to have an account of MailChimp in order to access Mandrill. If you haven’t created one yet, click here to do so.

Once done, logn to mailchimp account and click on profile -> transactional.

Nodejs and Mandrill

Click on Add Mandrill.

Nodejs and Mandrill

Mandrill is paid service but they allow for trial 2000 transaction emails. After reaching that limit, you need to buy the subscription.

Nodejs and Mandrill

Click on “Launch Mandrill”.

Nodejs and Mandrill

Click on “Setup your sending domain” button and add your domain name. It will ask you the email associated with the domain name in order to verify it.

Nodejs and Mandrill

It will send you an email, click on the link to verify your account.

Nodejs and Mandrill

Once verified you need to add two TXT record in your domain provider console.

1 : DKIM

Nodejs and Mandrill

2 : SPF

Nodejs and mandrill

After adding, test DNS setting.

Nodejs and mandrill

Now click on “SMTP & API info” and create new API key.

Nodejs and mandrill

That’s it you have your API key with you.

Integrating Mandrill in Node.js

We have covered this in the previous tutorial, but let’s cover it quickly for readers who directly coming to this post.

Create new folder and generate package.json. Use npm init to generate the package.json.

Install required dependencies using the following command.

npm install --save nodemailer nodemailer-mandrill-transport

Here is the code to send an email using Mandrill and Node.js

var nodemailer = require("nodemailer");
var mandrillTransport = require('nodemailer-mandrill-transport');

/*
* Configuring mandrill transport.
* Copy your API key here.
*/


var smtpTransport = nodemailer.createTransport(mandrillTransport({
    auth: {
      apiKey : '<< put your mandrill api key here >>'
    }
}));

// Put in email details.

let mailOptions={
   from : '[email protected]',
   to : '[email protected]',
   subject : "This is from Mandrill",
   html : "Hello,<br>Sending this email using Node and Mandrill"
};

// Sending email.
smtpTransport.sendMail(mailData, function(error, response){
  if(error) {
     throw new Error("Error in sending email");
  }
  console.log("Message sent: " + JSON.stringify(response));
});

That’s it. We have integrated Node.js and Mandrill to send an email.

Conclusion

We have covered creating Mandrill account and generated API key. We also integrated it in order to send an email using Node.js.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126