Send email from your Node.js application by using MailGun API services

Gobinda Thakur

[Update:- 07-Feb-2019]: Now my website is hosted on Netlify. Mailing functionality is not working currently. I am trying to fix it.

An application should able to communicate with its user. Nowadays sending transactional email is very important for establishing a healthy customer base. In my application, gobindathakur.com, I have implemented email service so that a person can contact me if he/she is interested in my profile or has any query.

You can navigate to “About Me” and then click on the button “Contact Me”. It will open the contact page. You just have to fill the details like your name, email address, subject and message. When you click on SUBMIT after filling all details, it will send an email to me with your message. You would also receive one email notification where I assure you to revert in short time. For this, we need a mail server.

What is Mail Server?

For sending or receiving emails, we need a mail server. There are two types of mail servers.

  1. Outgoing Mail Server (To send email): It uses Simple Mail Transfer Protocol(SMTP).
  2. Incoming Mail Server (To receive email): It uses Post Office Protocol Version 3 (POP3).

To integrate email service with Node.js application we have a lot of options. Most popular npm library is nodemailer.

For this we need

  1. Hostname
  2. SMTP port number
  3. Credentials (Username and Password)
// create reusable transporter object using the default SMTP transport     
let transporter = nodemailer.createTransport({
host: 'smtp.ethereal.email',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: account.user, // generated ethereal user
pass: account.pass // generated ethereal password
}
});

But I find easy while integrating MailGun with my application. For this we need

  1. Hostname (domain)
  2. API url
  3. API key

Here, no need to use username and password. So, let’s start with integration of MailGun API with Node.js application.

Step 1: Register with MailGun

Go to mailgun.com and signup.

MailGun Landing Page

Adding credit card detail is optional. Create your account after entering all required information.

The above page will show up after successful signup. You would receive an activation link in your mailbox as well. You can login to your account by clicking that link. Then it will ask for your phone number.

MailGun will send a verification code to your number. You have to enter that code to verify your account.

When you navigate to “Domains”. It will show you a domain which is created by MailGun by default for you development purpose.

By clicking on “Domain Name” you can see the details.

Step 2: Configure your domain in MailGun

You need to have a domain name for this. I already have my domain name with me which I purchased from godaddy.com.

Go to “Domains” in your MailGun page.

Click on “Add New Domain” button.

You can enter your domain name like mg.example.com as suggested. After adding the domain, it will ask you to configure some values with your DNS record.

Now go to godaddy.com and login to your account. Then navigate to “My Products”. Then open DNS Management console of your domain. And add MailGun DNS record to your Godaddy domain DNS record.

MailGun Console

Add both TXT value to DNS recors.

Godaddy DNS Management Console
Godaddy DNS Management Console

Then add MX value.

MailGun Console
Godaddy DNS Management Console
Godaddy DNS Management Console

Now we have to add CNAME value.

MailGun Console
Godaddy DNS Management Console

Finally, we have configured MailGun with our domain name.

Step 3: Install npm package to your Node.js Application

To use MailGun APIs, we have to install mailgun-js npm package in our application.

Go to you application directory and install the package

npm install --save mailgun-js

It will add mailgun-js to “dependencies” section of your package.json .

Inside you server directory, create a file email-config.js and add below code.

module.exports = () => {
const emailConfig = {
apiKey: '<your key>',
domain: '<your domain>'
};
return emailConfig;
};

You can get your api key and domain from your MailGun domain page.

MailGun page

Then create a file email-util.js and add below code.

const emailConfig = require('./email-config')();const mailgun = require('mailgun-js')(emailConfig);exports.sendEmail = (recipient, message, attachment) =>
new Promise((resolve, reject) => {
const data = {
from: 'Gobinda Thakur <info@mg.gobindathakur.com>',
to: recipient,
subject: message.subject,
text: message.text,
inline: attachment,
html: message.html,
};

mailgun.messages().send(data, (error) => {
if (error) {
return reject(error);
}
return resolve();
});
});

Create a express router sendMail.js

const express = require('express');
const sendMail = express.Router();
const emailUtil = require('./email-util');
const { sendEmail } = emailUtil;sendMail.post('/mail', async (req, res, next) => {
const { recipient, message } = req.body;
try {
await sendEmail(recipient, message);
res.json({message: 'Your query has been sent'});
await next();
} catch (e) {
await next(e);
}
});
module.exports = sendMail;

Then add the below code snippet in your server.js file for routing.

const express = require('express');
const app = express();
const sendMail = require('./sendMail');
app.use('/api/v1/communicate', sendMail);

From client you have to call API as below

URI: /api/v1/communicate/mail
Method: POST

Yes, finally we have done it!! Now your application is ready to communicate with it’s user.

Note:- You can send up to 10,000 mails for free. If you need more than this then you have to pay. One more thing that if you have entered your credit card details in MailGun then it will send mail to every email ids. Otherwise it will send email only to “Authorized Recipients”. You have to add it manually in MailGun.

MailGun Console

Conclusion

There are many mail service providers available. You can choose any one of them. They have come up with easy integrations with their APIs.


As requested, I have shared the client side code. Please check it out.

Gobinda Thakur

Written by

Fullstack web developer, www.gobindathakur.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade