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)
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.
More importantly, preview it before uploading.
Nice. It is very neat and clear for human to read