DEV Community

Cover image for Simple Nodemailer Usage
Jingtian Zhang
Jingtian Zhang

Posted on

Simple Nodemailer Usage

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

mkdir sample_mailer
cd sample_mailer
npm init -y // initialize npm 
npm install nodemailer
Enter fullscreen mode Exit fullscreen mode

then creating 2 files

touch index.js
touch index.html
Enter fullscreen mode Exit fullscreen mode

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 and paste in index.js:

"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);

Enter fullscreen mode Exit fullscreen mode

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

node index.js
// or define a "start" in package.json to run it
Enter fullscreen mode Exit fullscreen mode

my result shows:
Image description

and after clicking into the preview url, we will see this:
Image description

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

and here is the code:

<!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>
Enter fullscreen mode Exit fullscreen mode

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

const { promisify } = require("util");
const fs = require("fs");
const readFile = promisify(fs.readFile);
Enter fullscreen mode Exit fullscreen mode

and then replace the

html: "<b>Hello world?</b>", // html body
Enter fullscreen mode Exit fullscreen mode

with

html: await readFile("./index.html", "utf8"),
Enter fullscreen mode Exit fullscreen mode

then we run npm run start or node index.js again to run it, and check ethereal mail:
Image description

and if clicking on plain text option:

Image description

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.

Top comments (0)