Mails and Node JS
Tags: node, emails, javascript
Published: 2020-04-01 17:52:51

> The "[send emails in Node.js](https://blog.mailtrap.io/send-emails-with-nodejs/)" blog post originally was published on Mailtrap's blog.

Sending emails from Node.js is easy. We have gone over it in our previous blog post on [sending emails with Nodemailer](https://blog.mailtrap.io/sending-emails-with-nodemailer/). Last time we reviewed Nodemailer’s capabilities we focused on sending HTML emails via SMTP. In this post, we will examine how to send emails with Node.js using popular email servers like Gmail. Also, we will have a look at other transport options and packages to build and send emails from Node.js.&nbsp;&nbsp;

 
## Building and sending emails with Node.js without Nodemailer
 

In some guides and tutorials, you might find a note that there are a variety of Node.js email packages but Nodemailer is the best one. It’s not true. In fact, you can barely find a decent alternative to Nodemailer (and I can hardly imagine why you might need it.)

 

On Github, you can find several Node.js packages related to emails but they won’t offer you a wide functionality. With Nodemailer, you can create HTML emails with attachments and send them via SMTP, SES (wrapper for sending emails via AWS SES), or _sendmail_.&nbsp;

 

1. The most similar package is [Emaijs](https://github.com/eleith/emailjs). Its features include:&nbsp;

 
- sending emails via SMTP servers (both SSL and TLS) with authentication
- HTML support and MIME attachments (also, attachments can be added as strings, streams, or file paths)
- asynchronous sending of queued emails&nbsp;
- UTF-8 encoding in headers and body.

So, the main difference is that in Emailjs you will use MIME type to work with attachments, while in Nodemailer you use strings.&nbsp;

 

2. Another quite popular package is [email-templates](https://github.com/niftylettuce/email-templates). As you can see from the name, this package is designed for creating various custom templates for Node.js. It features support for automatic inline CSS, stylesheets, embedded images, and fonts. Also, it has an email preview option. The email templates package was made by the creator of the [Lad](https://lad.js.org/) framework. So it’s recommended to use it with Lad.&nbsp;

 

3. One more package worth mentioning here is [Mailgen](https://github.com/eladnava/mailgen). It is aimed at creating HTML templates for transactional emails. There is a note on Github, that with Mailgen you can “Programmatically create beautiful e-mails using plain old JavaScript.” The package includes several open-source themes as well as supports custom elements like tables, action buttons, etc. It is your choice how to send an email created with Mailgen, but they recommend checking out Nodemailer for this purpose.&nbsp;

 

| **Feature** | **Nodemailer** | **Emailjs** | **Email templates** | **Mailgen** |
| Building HTML emails | yes | Yes +MIME | Yes + CSS and customization | yes+CSS+themes |
| Email sending | SMTP, SES, _sendmail_ | SMTP | Lad | no |
| Github rating (stars) (as on June 25, 2019) | 11,258 | 1,748 | 2,489 | 2,223 |
| Last commit (as on June 25, 2019) | May 26, 2019 | Sept 4, 2018 | June 23, 2019 | Jan 3, 2019 |

As you can see from the above table, Nodemailer is the most popular package, which offers functionality for both email creation and email sending. It’s not limited to one sending method. But it won’t be easy to create a special email template. This is why it might be a good idea to use Nodemailer in combination with another package.

 

To find all related packages and plugins, [search for nodemailer](https://www.npmjs.com/search?q=nodemailer) in npm.

 
## Sending HTML emails with dynamic content
 

In our previous blog post, we reviewed [several examples of sending HTML emails](https://blog.mailtrap.io/sending-emails-with-nodemailer/) with Nodemailer, embedding images, and attaching files. In most cases, for transactional emails like registration confirmation or resetting passwords, you need to use dynamic content. It will be easier and more efficient to do it with one of the template modules.&nbsp;

 

Let’s experiment with the [email-templates](https://www.npmjs.com/package/email-templates) package. It has several interesting features:

 
- Support for different template engines ([Pug](https://pugjs.org/api/getting-started.html) is a default one)
- Email preview (by default) in the development environment
- Direct email sending. So, you don’t need extra packages like Nodemailer for email sending.&nbsp;

First of all, let’s create our templates, for a frequently occurring scenario: new user registration. In this example, we are working with the default option (for more details and samples of using Pug, refer to [Github](https://github.com/pugjs/pug).)&nbsp;

 

Install the template engine:

 

[npm](https://www.npmjs.com/):

 
```
npm install email-templates pug
```
 

[yarn](https://yarnpkg.com/):

 
```
yarn add email-templates pug
```
 

We should create two files: subject and HTML body.

 

_subject.pug:_

 
```
= `Hi ${firstName} ${lastName}, happy to see you at My App!`
```
 

_html.pug:_

 
```
h1 Hello #{firstName} #{lastName}
    p.
Welcome to My App! Now your test emails will be safe. We just need to make sure your account is real. 
Please, click the button below and start using your account. 
a(href='https://example.com/confirmation') Confirm!
```
 

Now make sure that your directory has the following structure:

 

├── app.js

 

├── emails

 

│ &nbsp; └── welcome (the template name)

 

│ &nbsp; &nbsp; &nbsp; ├── html.pug

 

│ &nbsp; &nbsp; &nbsp; ├── subject.pug

 

│ &nbsp; &nbsp; &nbsp; └── text.pug

 

Pay attention to the text part of your message: if you don’t include it, it will be generated automatically. But if you add it, it will be rendered automatically. This means that the content of the text and HTML parts may differ.&nbsp;

 

Now we can write some code to gather all the elements together and add transport. As usual, we will use [Mailtrap](https://mailtrap.io/), to be able to test and check everything. In the same way, you can use any other SMTP server like Gmail, for example. Just be careful if experimenting with real email addresses!

 

```
const Email = require('email-templates');
const email = new Email({
 message: {
   from: 'hi@example.com'
 },
 send: true,
 transport: {
   host: 'smtp.mailtrap.io',
   port: 2525,
   ssl: false,
   tls: true,
   auth: {
     user: '1a2b3c4d5e6f7g', // your Mailtrap username
     pass: '1a2b3c4d5e6f7g' //your Mailtrap password
   }
 }
});

const people = [
 {firstName: 'Diana', lastName: 'One'},
 {firstName: 'Alex', lastName: 'Another'}
];

people.forEach((person) => {
 email
   .send({
     template: 'welcome',
     message: {
       to: 'test@example.com'
     },
     locals: person
   })
   .then(console.log)
   .catch(console.error);
}).
```
 

By default, the preview of your email will be opened in your browser. It might be helpful if you are working on your template and don’t need to actually send the message. If you need to test how the variables work, and you compose a message to dozens or even hundreds of recipients, be careful with this option. To switch it off, specify _options.open_ as _false._

 

This is why we use Mailtrap: we will see how the message looks for each recipient, explore both HTML and text versions, and will be able to perform additional checks. With Pug and email-templates, you can build a complex template using CSS, inlined images, tables, etc. Here is an example of how it should look in the Mailtrap virtual inbox:

 
 ![](https://lh5.googleusercontent.com/TwdtkXu-XSEkbWE4ojpb2O2pBEXItu3oJtChPpaGvXnx9F3ZW4wCru1oTDe05yL4dUOWCdwWyw-eXzxQsfH3l58Rsna_07PXopB1ZCohOtKBsjqQDMCcGocd0ceO_AW2_s57STi1)* HTML*

 
 ![](https://lh3.googleusercontent.com/-pqsBEo-Mr4NVbcJQetksXWMSX2QhL-Cvy_pDqyf6CscXMTGxPK1s08HfW3WTulsHR5UO45ygUdA-XmePkso_dwiRhO3PHkGNB0Kk033vAr6shEDwK6wX0jBK7G63eLddvHu8VAg)* Text*

 
## Sending Emails with Nodemailer and SMTP
 

If configuring a new message in Nodemailer, we always should start with creating a transport method. The most popular one is the SMTP server, which can be easily set up for the majority of email clients or sending providers (like Sendgrid, Outlook, Gmail, etc.) SMTP configuration will be very simple and similar. For more detailed instructions on how to use Nodemailer, refer to the “[Sending emails with Nodemailer explained](https://blog.mailtrap.io/sending-emails-with-nodemailer/)” blog post.

 

Here we will demonstrate how to send emails with Gmail as it requires some tricks related to authentication.

 
## Sending emails with Gmail&nbsp;
 

To be able to use Gmail to send messages via your app, you should start with several account configurations.

 

If you use a **plain password** , then you should allow access for less secure apps.&nbsp;

 

If you are using **2-Step Verification** , you should sign in with [App Passwords.](https://support.google.com/accounts/answer/185833?hl=en) To create your password:

 
1. Go to the **Security** section of your [Gmail account](https://myaccount.google.com/).&nbsp;
2. Choose **App Passwords** in the **Signing into Google** block.
3. Select the app and device from the list and press **Generate**.&nbsp;

Please note that you can use it for your personal account only. It’s not available for accounts that are a part of an organization.&nbsp;

 

What else you should remember when setting the Gmail SMTP:

 
1. Gmail will automatically set the authenticated username as the _From_ email address. To change it, you should “Add another address you own”. You will find it in your Gmail account -\> Settings-\> Accounts. For more details, refer to this [Google Help Center article](https://support.google.com/mail/answer/22370?hl=en).&nbsp;
2. Gmail has its own [email limits](https://support.google.com/a/answer/166852?hl=en). For free (trial) accounts, it’s only 500 emails per day. If you reach the limit, your account might be suspended.&nbsp;

Now, when you made all necessary configurations, let’s set up the Gmail SMTP as a transport in the Node.js app.&nbsp;

 

Gmail SMTP hostname is `smtp.gmail.com`, the port should be 465 for SSL connection or 587 for TLS.

 
```
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL
    auth: {
        user: 'yourusername@gmail.com',
        pass: 'yourpassword'
    }
});
```
 

To avoid authentication issues, it is recommended to use oAuth2. Nodemailer requires an _Access Token_ to perform authentication. Read the instructions on the [Nodemailer documentation](https://nodemailer.com/usage/using-gmail/) to proceed with this method.&nbsp;

 

Once you have retrieved client ID and client Secret, refresh token and enable Gmail API at API console. It is recommended to use `bunyan` logger:

 
```
const bunyan = require('bunyan');
const nodemailer = require('../lib/nodemailer');

let logger = bunyan.createLogger({
    name: 'nodemailer'
});
logger.level('trace');
// Create a SMTP transporter object
let transporter = nodemailer.createTransport(
    {
        service: 'Gmail',
        auth: {
            type: 'OAuth2',
            user: 'mail',
            clientId: 'clientid',
            clientSecret: 'clientsecret',
            refreshToken: 'refreshtoken',
            accessToken: 'accesstoken',
            expires: 12345
        },
```
 

Otherwise, to get an access token, you can use [xoauth2](https://www.npmjs.com/package/xoauth2) package.&nbsp;

 
## Sending emails without SMTP&nbsp;
 

If you stick to one of the popular email sending providers like [Sendgrid, Mandrill, Mailgun](https://blog.mailtrap.io/sendgrid-vs-mandrill-vs-mailgun/), or Postmark, you can integrate your Node.js app with their API directly.

 

For AWS SES, there is a wrapper around Nodemailer, [node-ses](https://nodemailer.com/transports/ses/). You can use `aws-sdk` directly, but `node-ses` provides a simpler way to send complex email templates with images and attachments.&nbsp;

 
## Bottom line
 

If you are adding the email sending functionality to your Node.js app, most likely you will use Nodemailer. It is the simplest and most popular sending option compatible with other packages.&nbsp;

 

Besides, there are still options for how to send emails in Node.js without Nodemailer and without the SMTP server as well. Choose the option which best suits your current environment and needs. Just don’t forget to inspect and debug your test emails before delivering them to your customers.