Lately I was working on open source project that needs integration with hotmail to send emails out to user. I did pick up a story as an learning for me and ended up with creating a demo for this blog. I will like to share my learning below.
To send email from Node.js code we need to use nodemailer library. Nodemailer is a module for Node.js applications to allow easy as cake email sending. If you are able to run Node.js version 6 or newer, then you can use Nodemailer. There are no platform or resource specific requirements.
Also for creating demo, I made use of Ethereal email It is fake SMTP service that creates fake email and password for testing purpose and sandboxes the mail box.
You could see all the mails sent to the requested mail in the mailbox. Since it is sandbox environment, mail is not actually received in the real time.
We are going to create '/forgotpassword' api which will send email to user with password reset link.
const transporter = nodemailer.createTransport({
host: 'smtp.ethereal.email',
port: 587,
auth: {
user: process.env.ETHERAL_EMAIL,
pass: process.env.ETHERAL_PASSWORD
}
});
Email and password are stored and fetched from .env file created in root directory of project. This email and password is used to authenticate and send emails through EmailEngine.
Host in this example is 'smtp.ethereal.email' which could also be gmail, hotmail or office 365.
//gmail
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.email',
....
}
//hotmail
const transporter = nodemailer.createTransport({
host: 'smtp.hotmail.email',
....
}
// office 365
const transporter = nodemailer.createTransport({
host: 'smtp.office365.com',
....
});
And now we need to call sendMail method on transporter object passing 4 arguments from, to, subject and html.
const options = {
from: process.env.ETHERAL_EMAIL,
to: req.body.email,
subject: 'Reset Password',
html: `You are receiving this email because you(maybe someone else) wanted to change your password.\nIf it was not you, ignore this email.`
};
transporter.sendMail(options, (err, info) => {
if (err) {
console.log(err);
return res.status(400).json({ error: "Internal Server Error!" });
}
console.log(info.response);
return res.status(200).json({ success: "Email sent successfully!!" });
})
In the above example we are sending plain text email. We can also send html email by wrapping up html tags with strings.
Let's Test '/forgotpassword' endpoint in postman to verify response.
And in our mail box all outgoing mails are recorded.
That's it... Happy Coding!