DEV Community

Cover image for Sending Emails from NestJs Using the Mailgun API
Sandip Basnet
Sandip Basnet

Posted on

Sending Emails from NestJs Using the Mailgun API

Sending Emails from NestJs Using the Mailgun API

I had set up the mailing with nodemailer with mailgun few months back, that was working fine but I had got few recurring issues, that's why I have switched the implementation from SMTP to API, and I found it quite simpler than that of the SMTP as no extra library need to be used, apart from the request client axios.

The snippet of the implementation goes like this:

public async sendMail(mail: IMail) {
const mailOptions: MailInput = {
from: `SON <${configService.get('SENDER_EMAIL')}>`,
subject: mail.subject,
if (mail.template) {
const emailTemplateSource = fs.readFileSync(path.join(__dirname, `../../templates/${mail.template}.hbs`), "utf8")
const template = handlebars.compile(emailTemplateSource);
const htmlToSend = template(mail.templateVariables)
mailOptions.html = htmlToSend
} else {
mailOptions.text = mail.text;
try {
const body = Object.keys(mailOptions).map((key, index) => `${key}=${encodeURIComponent(mailOptions[key])}`).join('&');
const response = await`${configService.get('MAILGUN_DOMAIN')}/messages`,
auth: {
username: 'api',
password: configService.get('MAILGUN_API_KEY')
headers: {
"Content-Type": "application/x-www-form-urlencoded"
Logger.log(`Email successfully sent to: ${}.`)
return response;
} catch (error) {
Logger.warn(`Problem in sending email: ${error}`);
throw error;

Top comments (2)

fasunle profile image
Kehinde Hussein, Fasunle

Nice one ☺️ You could format this more neatly. It is not very readable. For example, if you want to show code, wrap it in 3 backticks.

Here is my code
Enter fullscreen mode Exit fullscreen mode

More importantly, preview it before uploading.

rahulranjanext profile image
Rahul Ranjan

Nice. It is very neat and clear for human to read