How to Send Email using Mailgun API in Node.js ?
Last Updated :
31 Mar, 2023
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: .
- It is easy to get started and easy to use.
- It is a widely used and popular module for sending emails.
- 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:
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'
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
If no error occurs, then go and check the receiver’s email inbox
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...