DEV Community

miku86
miku86

Posted on • Edited on

19 5

NodeJS: How To Send An Email

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?

Top comments (1)

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.

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay