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')}>`,
to: mail.to,
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 axios.post(`https://api.mailgun.net/v3/${configService.get('MAILGUN_DOMAIN')}/messages`,
body,
{
auth: {
username: 'api',
password: configService.get('MAILGUN_API_KEY')
},
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
Logger.log(`Email successfully sent to: ${mail.to}.`)
return response;
} catch (error) {
Logger.warn(`Problem in sending email: ${error}`);
throw error;
}
}

Top comments (0)

Thank you.

Β 
Thanks for visiting DEV, we’ve worked really hard to cultivate this great community and would love to have you join us. If you’d like to create an account, you can sign up here.