DEV Community

loading...

NodeJS: How To Send An Email

miku86 profile image miku86 Updated on ・1 min read

Intro

So we installed NodeJS on our machine.

We also know How to Get External Packages.

Now we want to learn how to send an email using nodemailer.

Write a simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
Enter fullscreen mode Exit fullscreen mode
  • Add this JavaScript code into it:
// import nodemailer (after npm install nodemailer)
const nodemailer = require('nodemailer');

// config for mailserver and mail, input your data
const config = {
  mailserver: {
    host: 'smtp.ethereal.email',
    port: 587,
    secure: false,
    auth: {
      user: 'yutfggtgifd7ixet@ethereal.email',
      pass: 'tX29P4QNadD7kAG7x5'
    }
  },
  mail: {
    from: 'foo@example.com',
    to: 'bar@example.com',
    subject: 'Hey',
    text: 'Testing Nodemailer'
  }
};

const sendMail = async ({ mailserver, mail }) => {
  // create a nodemailer transporter using smtp
  let transporter = nodemailer.createTransport(mailserver);

  // send mail using transporter
  let info = await transporter.sendMail(mail);

  console.log(`Preview: ${nodemailer.getTestMessageUrl(info)}`);
};

sendMail(config).catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Note: Nodemailer has a lot of available settings, therefore read the docs of nodemailer.


Run it from the terminal

  • Run it:
node index.js
Enter fullscreen mode Exit fullscreen mode
  • Result:
Preview: https://ethereal.email/message/XWk2jZDkEStePsCvXWk60Yf74VUAhgNZAAAACQqQo2lpzFsxaciWAqd9ZjY
Enter fullscreen mode Exit fullscreen mode

Further Reading


Questions

  • What is your favorite way/package to send mails in Node?
  • Do you automate some tasks with node emails?

Discussion (1)

pic
Editor guide
Collapse
stevetaylor profile image
Steve Taylor

Also take a look at mjml for creating emails that look consistent across numerous email clients with all their quirks. It’s an npm package and would work well in concert with nodemailer.