Send SMTP email with Node.js using Nodemailer
Tags: javascript, react, tutorial, todayilearned
Published: 2023-03-09 16:29:55


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](https://www.npmjs.com/package/nodemailer). 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](https://ethereal.email/create) It is fake SMTP service that creates fake email and password for testing purpose and sandboxes the mail box.

![Ethereal create](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aks4b371wkeh7kcfywek.png)

You could see all the mails sent to the requested mail in the [mailbox](https://ethereal.email/messages). Since it is sandbox environment, mail is not actually received in the real time.

![Ethereal mailbox](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xe1mfgijta0fu5qicroj.png)

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](https://emailengine.app/?utm_source=ethereal&utm_campaign=ethereal&utm_medium=hero-button).

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.
![Postman endpoint test](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/un1qh4086ar5ohgzlr8o.png)

And in our mail box all outgoing mails are recorded.

![Mailbox](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d1dnn7uwc8hgz26heuit.png)

That's it... Happy Coding!