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 (2)

Collapse
 
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.

Collapse
 
rahulranjanext profile image
Rahul Ranjan

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