Signup/Sign In

How to Send Email Using Nodemailer in NodeJs

This Nodejs tutorial will show you how to use nodemailer to send emails. The aim of this tutorial is to explain how to use Nodemailer. We'll concentrate on SMTP and HTML, but we'll go over all of Nodemailer's features as well. The makers of Nodemailer say that it makes sending emails a breeze.

Nodemailer is an npm bundle and plugin for Node.js applications that makes sending email as simple as possible. It's the most common Node.js email bundle.

Its major characteristics are as follows:

  • platform-independence
  • Unicode support
  • Embedded image attachments and HTML content
  • SMTP isn't the only mode of transport supported.

Installation

To get started with Nodemailer, you'll need Node.js version 6.0 or higher. In the Node.js console, run the following command:

npm install nodemailer 

When you've finished it, paste it into your application like this:

var nodemailer = require('nodemailer');

Sending Mails

To send a mail, there exist three major steps you should follow:

Create a Nodemailer transporter

The most popular transporter is SMTP, which we'll go into in more detail below.

All are fairly easy with SMTP. Set the host, port, authentication information, and process, and you're done. At this point, it's also a good idea to double-check that the SMTP link is working properly: use the verify(callback) method to validate the connection and authentication.

transporter.verify(function(error, success) {
   if (error) {
        console.log(error);
   } else {
        console.log('Server is ready to take our messages');
   }
});

If you wanna test you're nodemailer then on Ethereal, a fake SMTP service targeted primarily at Nodemailer users, you can use auto-generated email test accounts. Nodemailer recently released NodemailerApp. It's a Sendmail substitute, but it's first and foremost intended for email debugging. NodemailerApp includes SMTP and POP3 local servers, as well as a catchall email domain service and email preview.

Email options for Nodemailer

The sender, message recipients, and message content should all be specified at this stage. No additional attributes are needed to submit an HTML-formatted message; simply include the HTML body in the message with an HTML attribute. First, consider the following example of clear message options:

var mailOptions = {
    from: '"Example Team" <from@example.com>',
    to: 'user1@example.com, user2@example.com',
    subject: 'Nice Nodemailer test',
    text: 'Hey there, it’s our first message sent with Nodemailer ;) ', 
    html: '<b>Hey there! </b><br> This is our first message sent with Nodemailer'
};

The following key properties in Nodemailer can be used to apply various types of data to your message:

  • filename: the name of the file you've added.
  • content: your attachment's main body A series, a buffer, or a stream may all be used.
  • path: Instead of using it in the post, the path to the file is used to stream it. It is an excellent option for large attachments.
  • href: URL of the attachment Data URIs may also be used.
list: {
            // List-Help: <mailto:admin@example.com?subject=help>
            help: 'admin@example.com?subject=help',

            // List-Unsubscribe: <http://example.com> (Comment)
            unsubscribe: [
                {
                    url: 'http://example.com/unsubscribe',
                    comment: 'A short note about this url'
                },
                'unsubscribe@example.com'
            ],

            // List-ID: "comment" <example.com>
            id: {
                url: 'mylist.example.com',
                comment: 'my new list'
            }
        }
    };

Deliver a message with SendMail()

We can use the sendmail() method to send a message after we've built a transporter and configured it:

transport.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
});

Nodemailer Example

Let's implement the above method in this code example to send a mail.

var nodemailer = require('nodemailer');
var transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "1a2b3c4d5e6f7g",
    pass: "1a2b3c4d5e6f7g"
  }
});

var mailOptions = {
  from: '"Example Team" <from@example.com>',
  to: 'user1@example.com, user2@example.com',
  subject: 'Nice Nodemailer test',
  text: 'Hey there, it’s our first message sent with Nodemailer ',
  html: '<b>Hey there! </b><br> This is our first message sent with Nodemailer<br /><img src="cid:uniq-mailtrap.png" alt="mailtrap" />',
  attachments: [
    {
      filename: 'mailtrap.png',
      path: __dirname + '/mailtrap.png',
      cid: 'uniq-mailtrap.png' 
    }
  ]
};

transport.sendMail(mailOptions, (error, info) => {
  if (error) {
    return console.log(error);
  }
  console.log('Message sent: %s', info.messageId);
});

Output:

Conclusion

We went over how to use Nodemailer to generate and send emails via SMTP, playing with various types of content such as HTML, tables, lists, attachments, and embedded photos. What's great about Nodemailer is that it has a tonne of different choices and configurations, allowing you to personalize every aspect of your email.

The makers of Nodemailer rightly claimed that it makes sending emails a breeze we got no doubt about it.



About the author: