reCAPTCHA WAF Session Token
Programming Languages

Sending Email Using Node.js — SitePoint

Most web applications need to send email. It may be for registration, password resets, status reports, though to full marketing campaigns such as newsletters and promotions. This tutorial explains how to send email in Node.js, but the concepts and challenges apply to whatever systems you’re using.

You’ll find plenty of email-related modules on npm. The most popular is NodeMailer, which receives more than three million downloads every week.

To use it, you’ll require an SMTP server which can send email. You may be able to use your own email provider but, for the purposes of this demonstration, I’m using the free WPOven Test SMTP Server.

Create a new project folder:

<code class="bash language-bash"><span class="token function">mkdir</span> emailtest
<span class="token builtin class-name">cd</span> emailtest
</code>

Then create a new package.json file with the following JSON content:

<code class="javascript language-javascript"><span class="token punctuation">{</span>
  <span class="token string">"name"</span><span class="token operator">:</span> <span class="token string">"emailtest"</span><span class="token punctuation">,</span>
  <span class="token string">"type"</span><span class="token operator">:</span> <span class="token string">"module"</span><span class="token punctuation">,</span>
  <span class="token string">"main"</span><span class="token operator">:</span> <span class="token string">"index.js"</span><span class="token punctuation">,</span>
  <span class="token string">"dependencies"</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token string">"nodemailer"</span><span class="token operator">:</span> <span class="token string">"^6.0.0"</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code>

Install the modules (NodeMailer):

<code class="bash language-bash"><span class="token function">npm</span> <span class="token function">install</span>
</code>

and create the following index.js code:

<code class="javascript language-javascript"><span class="token keyword module">import</span> <span class="token imports">nodemailer</span> <span class="token keyword module">from</span> <span class="token string">'nodemailer'</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> transporter <span class="token operator">=</span> nodemailer<span class="token punctuation">.</span><span class="token method function property-access">createTransport</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  host<span class="token operator">:</span> <span class="token string">'smtp.freesmtpservers.com'</span><span class="token punctuation">,</span>
  port<span class="token operator">:</span> <span class="token number">25</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword control-flow">try</span> <span class="token punctuation">{</span>

  <span class="token keyword">const</span> send <span class="token operator">=</span> <span class="token keyword control-flow">await</span> transporter<span class="token punctuation">.</span><span class="token method function property-access">sendMail</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    <span class="token keyword module">from</span><span class="token operator">:</span> <span class="token string">'"Test Email" <test@email.com>'</span><span class="token punctuation">,</span>  
    to<span class="token operator">:</span> <span class="token string">'someone@example.com'</span><span class="token punctuation">,</span>              
    subject<span class="token operator">:</span> <span class="token string">'Hello!'</span><span class="token punctuation">,</span>                      
    text<span class="token operator">:</span> <span class="token string">'Hello world!'</span><span class="token punctuation">,</span>                   
    html<span class="token operator">:</span> <span class="token string">'<p>Hello world!</p>'</span><span class="token punctuation">,</span>            
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token console class-name">console</span><span class="token punctuation">.</span><span class="token method function property-access">dir</span><span class="token punctuation">(</span>send<span class="token punctuation">,</span> <span class="token punctuation">{</span> depth<span class="token operator">:</span> <span class="token keyword null nil">null</span><span class="token punctuation">,</span> color<span class="token operator">:</span> <span class="token boolean">true</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span>
<span class="token keyword control-flow">catch</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token punctuation">{</span>

  <span class="token console class-name">console</span><span class="token punctuation">.</span><span class="token method function property-access">dir</span><span class="token punctuation">(</span>e<span class="token punctuation">,</span> <span class="token punctuation">{</span> depth<span class="token operator">:</span> <span class="token keyword null nil">null</span><span class="token punctuation">,</span> color<span class="token operator">:</span> <span class="token boolean">true</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span>
</code>

(Consider changing the to: address to something unique so you can examine your own test emails!)

Run the code. You should see a result with a 250 OK response and a messageId:

<code class="bash language-bash">$ node index.js
<span class="token punctuation">{</span>
  accepted: <span class="token punctuation">[</span> <span class="token string">'someone@example.com'</span> <span class="token punctuation">]</span>,
  rejected: <span class="token punctuation">[</span><span class="token punctuation">]</span>,
  ehlo: <span class="token punctuation">[</span> <span class="token string">'SIZE 33554432'</span>, <span class="token string">'8BITMIME'</span>, <span class="token string">'SMTPUTF8'</span>, <span class="token string">'HELP'</span> <span class="token punctuation">]</span>,
  envelopeTime: <span class="token number">486</span>,
  messageTime: <span class="token number">289</span>,
  messageSize: <span class="token number">595</span>,
  response: <span class="token string">'250 OK'</span>,
  envelope: <span class="token punctuation">{</span>
    from: <span class="token string">'test@email.com'</span>,
    to: <span class="token punctuation">[</span> <span class="token string">'someone@example.com'</span> <span class="token punctuation">]</span>
  <span class="token punctuation">}</span>,
  messageId: <span class="token string">'<4673597e-a9e4-e422-85f7-4422edf31774@email.com>'</span>
<span class="token punctuation">}</span>
</code>

Check the inbox of the to: address you used by entering it at the WPOven Test SMTP Server page and clicking Access Inbox. Click the “Hello!” message to examine the content.

NodeMailer Basics

To send emails, you must create a NodeMailer transporter object to define the service type. SMTP is most common, but others are available for alternative services. An authentication user ID and password is usually necessary:

<code class="javascript language-javascript"><span class="token keyword module">import</span> <span class="token imports">nodemailer</span> <span class="token keyword module">from</span> <span class="token string">'nodemailer'</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> transporter <span class="token operator">=</span> nodemailer<span class="token punctuation">.</span><span class="token method function property-access">createTransport</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  host<span class="token operator">:</span> <span class="token string">'smtp.yourserver.com'</span><span class="token punctuation">,</span>
  port<span class="token operator">:</span> <span class="token number">587</span><span class="token punctuation">,</span>
  auth<span class="token operator">:</span> <span class="token punctuation">{</span>
    user<span class="token operator">:</span> <span class="token string">'myid@yourserver.com'</span><span class="token punctuation">,</span>
    pass<span class="token operator">:</span> <span class="token string">'my-password'</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code>

You can send emails to one or more recipients using the transporter’s sendMail() method:

<code class="javascript language-javascript"><span class="token keyword">const</span> send <span class="token operator">=</span> <span class="token keyword control-flow">await</span> transporter<span class="token punctuation">.</span><span class="token method function property-access">sendMail</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token keyword module">from</span><span class="token operator">:</span> <span class="token string">'"Test Email" <test@email.com>'</span><span class="token punctuation">,</span>          
  to<span class="token operator">:</span> <span class="token string">'someone@example.com, sometwo@example.com'</span><span class="token punctuation">,</span> 
  cc<span class="token operator">:</span> <span class="token string">'somethree@example.com'</span><span class="token punctuation">,</span>
  bcc<span class="token operator">:</span> <span class="token string">'somefour@example.com'</span><span class="token punctuation">,</span>
  subject<span class="token operator">:</span> <span class="token string">'Hello!'</span><span class="token punctuation">,</span>                              
  text<span class="token operator">:</span> <span class="token string">'Plain text version of the message'</span><span class="token punctuation">,</span>      
  html<span class="token operator">:</span> <span class="token string">'<p>HTML version of the message</p>'</span><span class="token punctuation">,</span>     
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code>

All email clients support plain text messages. You can also send a rich-formatted version of the same message used when the email client supports HTML (more about that below).

NodeMailer provides plenty of other messaging options, but the most common is attachments. An array of objects defines filenames and content. For example:

<code class="javascript language-javascript"><span class="token keyword">const</span> send <span class="token operator">=</span> <span class="token keyword control-flow">await</span> transporter<span class="token punctuation">.</span><span class="token method function property-access">sendMail</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  
  attachments<span class="token operator">:</span> <span class="token punctuation">[</span>
    <span class="token punctuation">{</span> 
      filename<span class="token operator">:</span> <span class="token string">'text1.txt'</span><span class="token punctuation">,</span>
      path<span class="token operator">:</span> <span class="token string">'/path/to/file1.txt'</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">{</span>  
      filename<span class="token operator">:</span> <span class="token string">'text2.txt'</span><span class="token punctuation">,</span>
      path<span class="token operator">:</span> <span class="token string">'</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">{</span> 
      filename<span class="token operator">:</span> <span class="token string">'text3.txt'</span><span class="token punctuation">,</span>
      content<span class="token operator">:</span> <span class="token string">'This is the file content!'</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">{</span> 
      filename<span class="token operator">:</span> <span class="token string">'text4.txt'</span><span class="token punctuation">,</span>
      path<span class="token operator">:</span> <span class="token string">'data:text/plain;base64,SGVsbG8gd29ybGQh'</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">]</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code>

Sending Services

It’s easy to send simple one-off emails, but please don’t underestimate challenge as your requirements evolve.

  1. You may not have an SMTP server. Not all email services provide SMTP (Google is withdrawing basic SMTP support in Gmail).

  2. Most services limit outgoing emails. If you’re sending many emails, you may hit your provider’s limit. At that point, all emails going through the same service will fail: that’s your newsletter as well as personal and business messages.

  3. You may become a spammer. It’s easy for recipients to mark your email as “junk” — even when it’s not. When enough people do that, you could discover all emails from your domain become blocked across the Internet.

It’s better to use a dedicated email service rather than your own mail server. The following services reduce the potential problems and some offer free plans for those with low usage requirements:

Asynchronous application architecture

Sending a single email is often fast, but:

  • the SMTP server could be down so retries are necessary, or
  • the message could get caught in the middle of a bulk newsletter posting

Rather than sending emails directly within your Node.js application, it’s generally better to send the data to a task queue. The end user need not wait for a response and can continue to use the app.

Another process can monitor the email queue, send the next message, and requeue items when a failure occurs.

Crafting HTML Emails

HTML5 and CSS3 work consistently well in modern browsers. Email clients are another matter, taking us back to the frustrating late 1990s days of tables and inline styles.

These are some of the issues you’ll face:

  • There are dozens of native and web-based email clients including Gmail, Yahoo Mail, Apple Mail, iOS Mail, Android Mail, Windows Mail, Outlook, Outlook.com, (new) Outlook, Thunderbird, AOL, Claws, RoundCube, and so on.

  • All use their own weird and wonderful rendering engines with unique issues and bugs. Somewhat bizarrely, Outlook has used Microsoft Word to render HTML since 2007 (although the new preview version is browser based).

  • Most clients block or limit fonts, images, trackers, media queries, iframes, videos, audio, forms, and scripts.

  • Even web-based email clients running in the browser must remove HTML, CSS, and JavaScript that’s dangerous or that could affect UI layout. For example, it shouldn’t be possible for an email to auto-click its own links or absolutely position an element over a delete button.

  • Email clients can reformat your HTML to ensure it’s a single column or adheres with the user’s light/dark mode preferences.

It’s possible to hand-code HTML emails but, unless your layout is simple, it’s a difficult, frustrating, and error-prone. The following sections suggest tools and resources that may make your life easier.

Pre-built email templates

The following sites provide free and commercial robust email templates you can preview, download, and use with minimal effort:

Email template design tools

The following no-code design tools allow you to create your own HTML email templates using a simpler WYSWYG editor:

Some of these services also provide code validation and testing facilities.

Email template conversion

Premailer is a web tool which takes a page URL or pasted source code and transforms it to email-compatible HTML and plain text templates. There’s a REST API and Node.js premailer-api module should you need to automate the process.

Similar tools include:

Email template markup tools

Cerberus, Email Framework, Email Skeleton, and Good Email Code provide HTML component snippets you can copy and adapt in your own templates.

HEML and MJML are email markup languages. They’re similar to HTML but prevent typical compatibility issues. Maizzle takes a similar approach using Tailwind CSS.

Parcel is a code editor which understands email formatting and can show previews. You’ll also find plenty of email extensions for VS Code.

caniemail.com is the email equivalent of the web page caniuse.com and reports whether a specific HTML or CSS feature is usable across multiple clients. Finally, Accessible Email provides associated resources and links.

Email testing tools

While an HTML email may work in your own email apps, can you be sure it works in others? The following tools will help, but there’s no substitute for testing a range of real devices, OSes, and email clients.

HTML Email Check and MailTrap validate your source code and report problems you could encounter in specific clients.

emailpreview, Mailosaur, and Email Preview Services provide layout preview facilities so you can check how your design will look on a variety of clients.

Finally, Litmus and Email on Acid have a range of tools to validate code, check accessibility, preview across clients, record analytics, and run full marketing campaigns.

Learn how to code emails the right way

As we’ve seen above, there are many tools that can help you to create email layouts that work across the many email clients out there. But there’s nothing like understanding how to code all by yourself, especially when you need to sort out the inevitable bugs that arise.

If you’d like to learn the ins and outs of email coding (even if it’s just as a backup), check out Crafting HTML Email, by Rémi Parmentier. It covers modern perspectives on building your own email templates, essential best practices, how to add interactivity to emails, and how to make your templates accessible. It even walks you through a case study to see all this in practice.

Reading Incoming Email

Most apps need only send emails, but there may be occasions when you want to examine incoming emails — for things like service registration, unsubscribe handling, automated support, and so on. While it’s beyond the scope of this tutorial, Node.js modules such as ImapFlow allow your application to connect to an IMAP inbox, fetch messages, and process a response:

<code class="javascript language-javascript"><span class="token keyword module">import</span> <span class="token imports"><span class="token maybe-class-name">ImapFlow</span></span> <span class="token keyword module">from</span> <span class="token string">'imapflow'</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> client <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ImapFlow</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    host<span class="token operator">:</span> <span class="token string">'imap.email'</span><span class="token punctuation">,</span>
    port<span class="token operator">:</span> <span class="token number">993</span><span class="token punctuation">,</span>
    secure<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
    auth<span class="token operator">:</span> <span class="token punctuation">{</span>
        user<span class="token operator">:</span> <span class="token string">'account@imap.email'</span><span class="token punctuation">,</span>
        pass<span class="token operator">:</span> <span class="token string">'mypassword'</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword control-flow">try</span> <span class="token punctuation">{</span>

  
  <span class="token keyword control-flow">await</span> client<span class="token punctuation">.</span><span class="token method function property-access">connect</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  
  <span class="token keyword">const</span> lock <span class="token operator">=</span> <span class="token keyword control-flow">await</span> client<span class="token punctuation">.</span><span class="token method function property-access">getMailboxLock</span><span class="token punctuation">(</span><span class="token string">'INBOX'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  
  <span class="token keyword">const</span> msg <span class="token operator">=</span> <span class="token keyword control-flow">await</span> client<span class="token punctuation">.</span><span class="token method function property-access">fetchOne</span><span class="token punctuation">(</span>client<span class="token punctuation">.</span><span class="token property-access">mailbox</span><span class="token punctuation">.</span><span class="token property-access">exists</span><span class="token punctuation">,</span> <span class="token punctuation">{</span> source<span class="token operator">:</span> <span class="token boolean">true</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token console class-name">console</span><span class="token punctuation">.</span><span class="token method function property-access">log</span><span class="token punctuation">(</span> msg<span class="token punctuation">.</span><span class="token property-access">source</span><span class="token punctuation">.</span><span class="token method function property-access">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">)</span><span class="token punctuation">;</span>

  
  lock<span class="token punctuation">.</span><span class="token method function property-access">release</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  
  <span class="token keyword control-flow">await</span> client<span class="token punctuation">.</span><span class="token method function property-access">logout</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span>
<span class="token keyword control-flow">catch</span> <span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token console class-name">console</span><span class="token punctuation">.</span><span class="token method function property-access">log</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code>

Conclusion

Sending emails from Node.js web apps is easy. Sending emails which look good, work reliably in all email clients, don’t halt the user, and don’t cause spam woes can be considerably more difficult.

I recommend you keep emails simple to start, perhaps opting for infrequent plain text messages. Of course, your clients and marketing department will soon want fancy colors and animations, but you can deliver that tomorrow!

Frequently Asked Questions (FAQs) about Sending Emails Using Node.js

How can I attach files to my emails using Node.js?

Attaching files to your emails using Node.js is quite straightforward. You can use the ‘attachments’ property in the mail options. This property takes an array of attachment options. Each attachment option is an object that contains the filename and path properties. The filename property is the name of the file as it will appear in the email, and the path property is the location of the file on your system.

Here’s an example:

<code>let mailOptions = {</code><br><code>from: 'sender@example.com',</code><br><code>to: 'receiver@example.com',</code><br><code>subject: 'Hello',</code><br><code>text: 'Hello world',</code><br><code>attachments: [</code><br><code>{</code><br><code>filename: 'file.txt',</code><br><code>path: '/path/to/file.txt'</code><br><code>}</code><br><code>]</code><br><code>};</code>

Can I send HTML emails using Node.js?

Yes, you can send HTML emails using Node.js. Instead of using the ‘text’ property in the mail options, you use the ‘html’ property. The value of this property is the HTML content of the email.

Here’s an example:

<code>let mailOptions = {</code><br><code>from: 'sender@example.com',</code><br><code>to: 'receiver@example.com',</code><br><code>subject: 'Hello',</code><br><code>html: '<h1>Hello world</h1>'</code><br><code>};</code>

How can I send emails to multiple recipients?

To send emails to multiple recipients, you can provide a list of email addresses separated by commas in the ‘to’ property of the mail options.

Here’s an example:

<code>let mailOptions = {</code><br><code>from: 'sender@example.com',</code><br><code>to: 'receiver1@example.com, receiver2@example.com',</code><br><code>subject: 'Hello',</code><br><code>text: 'Hello world'</code><br><code>};</code>

How can I handle errors when sending emails?

You can handle errors when sending emails by using a callback function. This function is passed as the second argument to the ‘sendMail’ method. The callback function takes two parameters: an error object and an info object. If an error occurs when sending the email, the error object will contain information about the error.

Here’s an example:

<code>transporter.sendMail(mailOptions, function(error, info){</code><br><code>if (error) {
console.log(error);
} else {console.log('Email sent: ' + info.response);
}
});</code>

Can I use a Gmail account to send emails?

Yes, you can use a Gmail account to send emails. However, you need to enable ‘Less secure apps’ in your Gmail account settings. Also, you need to use ‘smtp.gmail.com’ as the host and 587 as the port in the transporter options.

Here’s an example:

<code>let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
auth: {
user: 'your-email@gmail.com',
pass: 'your-password'
}
});</code>

How can I send emails asynchronously?

You can send emails asynchronously by using Promises. The ‘sendMail’ method returns a Promise that resolves with an info object when the email is sent.

Here’s an example:

<code>transporter.sendMail(mailOptions)
.then(info => console.log('Email sent: ' + info.response))
.catch(error => console.log(error));</code>

Can I use a custom SMTP server to send emails?

Yes, you can use a custom SMTP server to send emails. You need to provide the host, port, and authentication details of the SMTP server in the transporter options.

Here’s an example:

<code>let transporter = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587,
auth: {
user: 'username',
pass: 'password'
}
});</code>

How can I send emails with a specific charset?

You can send emails with a specific charset by using the ‘charset’ property in the mail options. This property sets the charset of the email.

Here’s an example:

<code>let mailOptions = {
from: 'sender@example.com',
to: 'receiver@example.com',
subject: 'Hello',
text: 'Hello world',
charset: 'UTF-8'
};</code>

Can I send emails with a specific content type?

Yes, you can send emails with a specific content type. You can use the ‘contentType’ property in the mail options. This property sets the content type of the email.

Here’s an example:

<code>let mailOptions = {
from: 'sender@example.com',
to: 'receiver@example.com',
subject: 'Hello',
text: 'Hello world'
contentType: 'text/plain
};</code>

How can I send emails with a specific encoding?

You can send emails with a specific encoding by using the ‘encoding’ property in the mail options. This property sets the encoding of the email.

Here’s an example:

<code>let mailOptions = {
from: 'sender@example.com',
to: 'receiver@example.com',
subject: 'Hello',
text: 'Hello world',
encoding: 'base64'
};</code>

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
WP Twitter Auto Publish Powered By : XYZScripts.com
SiteLock