Open In App

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

Last Updated : 31 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 a widely used and popular module for sending emails.
  3. Mails can also be scheduled.

Installation of Mailgun module:  

You can visit the link to Install mailgun module. You can install this package by using the following command. 

npm install mailgun-js

After installing mailgun you can check your mailgun version in the command prompt using the command. 

npm version mailgun-js

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

Requiring module: You need to include mailgun module in your file by using these lines. 

const mailgun = require('mailgun-js');

Project Structure:

project structure

Filename: 

index.js 

javascript




let API_KEY = 'Your_Api_Key';
let DOMAIN = 'Your_Domain';
const 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);
    });
}
 
let sender_email = 'sender@gmail.com'
let receiver_email = 'receiver@gmail.com'
let email_subject = 'Mailgun Demo'
let 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: 

Make sure you have installed mailgun using the following commands: 

npm install mailgun-js

Run the index.js file using the following command: 

node index.js

Output of above command

If no error occurs, then go and check the receiver’s email inbox  

receiver-inbox 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads