Simple Nodemailer Usage
Tags: webdev, node
Published: 2022-03-02 13:07:02

Nodemailer is a module for Node.js applications to allow easy as cake email sending, and here let's create a simple nodemailer application so user can send some sample mails locally.

## First, lets build a project and send a text message

```bash
mkdir sample_mailer
cd sample_mailer
npm init -y // initialize npm 
npm install nodemailer
```
then creating 2 files 

```bash
touch index.js
touch index.html
```
we will first try send a simple message and check it on ethereal mail, and then send a real html-based mail, thats why we need `index.html`

next, copy and paste the code from [nodemailer's website](https://nodemailer.com/about/) and paste in `index.js`: 

```javascript
"use strict";
const nodemailer = require("nodemailer");

// async..await is not allowed in global scope, must use a wrapper
async function main() {
  // Generate test SMTP service account from ethereal.email
  // Only needed if you don't have a real mail account for testing
  let testAccount = await nodemailer.createTestAccount();

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: testAccount.user, // generated ethereal user
      pass: testAccount.pass, // generated ethereal password
    },
  });

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: '"Fred Foo 👻" <foo@example.com>', // sender address
    to: "bar@example.com, baz@example.com", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world?", // plain text body
    html: "<b>Hello world?</b>", // html body
  });

  console.log("Message sent: %s", info.messageId);
  // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

  // Preview only available when sending through an Ethereal account
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

main().catch(console.error);

```

in this case, we will create a nodemailer transport object and use testAccount and send a sample mail and check in its generated address: 

```bash
node index.js
// or define a "start" in package.json to run it
```

my result shows: 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ebkvjwo17g3u1tkah97.png)

and after clicking into the preview url, we will see this: 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zh4wapo1zrw8982x7t9u.png)

## Second, lets send an HTML

lets create that `index.html` file, we found an image from `unsplash.com` and put some words in the html file, finally it looks like this: 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zbfj4u40jzrfc07nagp6.png)

and here is the code: 

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=s, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <h1>hello title</h1>
      <p>this is the main body text here</p>
      <span>lalalalalalall</span>
      <img
        src="https://images.unsplash.com/photo-1646186598644-0b0e407852a6?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1036&q=80"
        alt=""
      />
    </div>
  </body>
</html>
```

while lets tune the `index.js` file a little bit to make it send this file

first, we have to read it using node.js's built-in `fs` module

```javascript
const { promisify } = require("util");
const fs = require("fs");
const readFile = promisify(fs.readFile);
```

and then replace the

```javascript
html: "<b>Hello world?</b>", // html body
``` 

with 

```javascript 
html: await readFile("./index.html", "utf8"),
``` 

then we run `npm run start` or `node index.js` again to run it, and check ethereal mail: 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ebxq2r23i0k416du2pz.png)

and if clicking on `plain text` option: 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxflfzjxy5pfp5kbxb7c.png)

*Hooray, we have the first text and html message sent!* Later we are gonna check how to build fancier email applications based on nodemailer to make our daily work more productive.