Join us
@sofiatarhonska ă» Sep 16,2022 ă» 9 min read ă» 1971 views ă» Originally posted on mailtrap.io
Sending emails from Node.js is easy. We have gone over it in our previous blog post on 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.
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.Â
1.The most similar package is Emaijs. Its features include:Â
So, the main difference is that in Emailjs you will use MIME type to work with attachments, while in Nodemailer you use strings.Â
2. Another quite popular package is 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 framework. So itâs recommended to use it with Lad.Â
3.One more package worth mentioning here is 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 emails 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.Â
Nodemailer is the most popular package, which offers functionality for both email creation and email sending, period. Itâs not limited to one sending method. But it wonât be easy to create a special email template. With no real alternative that surpasses Nodemailer in functionality, the optimal route is using it in combination with another package.
To find all related packages and plugins, search for nodemailer in npm.
Before we dive into reviewing how dynamic content works with HTML emails, itâs worth mentioning a new package that was just released in June 2022. Mailtrapâs very own sending package! Mailtrap provides both sending and testing functionality, and we always aim at saving everyone time and simply making life easier. With that in mind, it only made sense for us to make a package that allows developers to add a sending functionality to a Node.js application quickly. Additionally, it offers integration with the official API for Mailtrap and will be integrated with Nodemailer in the near future.
Install the Mailtrap package:Â
yarn:
yarn add mailtrap
npm:
npm install mailtrap
To further proceed with adding sending functionality to your Node.js application refer here for the source code.
If you want to find any issues that can lead to bugs or other inconsistencies use yarn lint
with ESLint.
In our previous blog post, we reviewed several examples of sending HTML emails 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.Â
Letâs experiment with the email-templates package. It has several interesting features:
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.)Â
Install the template engine:
npm:
npm install email-templates pug
Copy
yarn:
yarn add email-templates pug
Copy
We should create two files: subject and HTML body.
subject.pug:
= `Hi ${firstName} ${lastName}, happy to see you at My App!`
Copy
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!
Copy
Now make sure that your directory has the following structure:
âââ app.js
âââ emails
â âââ welcome (the template name)
â âââ html.pug
â âââ subject.pug
â âââ text.pug
Copy
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.Â
Now we can write some code to gather all the elements together and add transport. As usual, we will use Mailtrap, 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);
}).
Copy
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:
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â blog post.
Here we will demonstrate how to send emails with Gmail as it requires some tricks related to authentication.
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.Â
If you are using 2-Step Verification, you should sign in with App Passwords. To create your password:
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.Â
What else you should remember when setting the Gmail SMTP:
Now, when you made all necessary configurations, letâs set up the Gmail SMTP as a transport in the Node.js app.Â
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'
}
});
Copy
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 to proceed with this method.Â
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
},
Copy
Otherwise, to get an access token, you can use xoauth2 package.Â
For more detailed instructions on using Gmail, refer to our Nodemailer Gmail Tutorial.
If you stick to one of the popular email sending providers like Sendgrid, Mandrill, 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. You can use aws-sdk
directly, but node-ses
provides a simpler way to send complex email templates with images and attachments.Â
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.Â
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.
And, with Mailtrap, you can do both in one swell swoop. Our Mailtrap Email API offers quick setup and deliverability monitoring after you inspect and debug your emails using Mailtrap Email Sandbox.
Thank you for reading our article which was originally published on Mailtrap Blog in an in-depth guide on sending emails in Node.js through SMTP.
Join other developers and claim your FAUN account now!
Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.