Skip to content
Related Articles

Related Articles

How to Send Email using Mailgun API in Node.js ?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 05 May, 2021
View Discussion
Improve Article
Save Article

Sending an email is an essential part of any project and it can be achieved by using Mailgun API. It is very popular for sending emails.
Features of Mailgun:

  1. It is easy to get started and easy to use.
  2. It is widely used and popular module for sending emails.
  3. Mails can also be scheduled.

Installation of Mailgun module: 

  1. You can visit the link to Install mailgun module. You can install this package by using the following command. 
npm install mailgun-js
  1. After installing mailgun you can check your mailgun version in command prompt using the command. 
npm version mailgun-js
  1. After that, you can create a folder and add a file. For example index.js. To run this file you need to run the following command. 
node index.js
  1. Requiring module: You need to include mailgun module in your file by using these lines. 
const mailgun = require('mailgun-js');

Filename: index.js 


var API_KEY = 'Your_Api_Key';
var DOMAIN = 'Your_Domain';
var mailgun = require('mailgun-js')
       ({apiKey: API_KEY, domain: DOMAIN});
sendMail = function(sender_email, receiver_email,
         email_subject, email_body){
  const data = {
    "from": sender_email,
    "to": receiver_email,
    "subject": email_subject,
    "text": email_body
  mailgun.messages().send(data, (error, body) => {
    if(error) console.log(error)
    else console.log(body);
var sender_email = ''
var receiver_email = ''
var email_subject = 'Mailgun Demo'
var email_body = 'Greetings from geeksforgeeks'
// User-defined function to send email
sendMail(sender_email, receiver_email,
            email_subject, email_body)

Steps to run the program: 

  1. The project structure will look like this: 

project structure

  1. Make sure you have installed mailgun using the following commands: 
npm install mailgun-js
  1. Run index.js file using the following command: 
node index.js

Output of above command

  1. If no error occurs, then go and check the receiver email inbox 



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!