Most internet purposes have to ship e mail. It could be for registration, password resets, standing studies, although to full advertising and marketing campaigns similar to newsletters and promotions. This tutorial explains how one can ship e mail in Node.js, however the ideas and challenges apply to no matter programs you’re utilizing.
You’ll discover loads of email-related modules on npm. The preferred is NodeMailer, which receives greater than three million downloads each week.
To make use of it, you’ll require an SMTP server which may ship e mail. You could possibly use your personal e mail supplier however, for the needs of this demonstration, I’m utilizing the free WPOven Test SMTP Server.
Create a brand new venture folder:
mkdir emailtest
cd emailtest
Then create a brand new bundle.json
file with the next JSON content material:
{
"identify": "emailtest",
"kind": "module",
"most important": "index.js",
"dependencies": {
"nodemailer": "^6.0.0"
}
}
Set up the modules (NodeMailer):
npm set up
and create the next index.js
code:
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
host: 'smtp.freesmtpservers.com',
port: 25
});
strive {
const ship = await transporter.sendMail({
from: '"Take a look at Electronic mail" ' ,
to: '[email protected]',
topic: 'Hey!',
textual content: 'Hey world!',
html: 'Hey world!
',
});
console.dir(ship, { depth: null, shade: true });
}
catch(e) {
console.dir(e, { depth: null, shade: true });
}
(Think about altering the to:
deal with to one thing distinctive so you’ll be able to study your personal take a look at emails!)
Run the code. It is best to see a end result with a 250 OK
response
and a messageId
:
$ node index.js
{
accepted: [ '[email protected]' ],
rejected: [],
ehlo: [ 'SIZE 33554432', '8BITMIME', 'SMTPUTF8', 'HELP' ],
envelopeTime: 486,
messageTime: 289,
messageSize: 595,
response: '250 OK',
envelope: {
from: 'take a look at@e mail.com',
to: [ '[email protected]' ]
},
messageId: ''
}
Verify the inbox of the to:
deal with you utilized by getting into it on the WPOven Test SMTP Server page and clicking Entry Inbox. Click on the “Hey!” message to look at the content material.
NodeMailer Fundamentals
To ship emails, you will need to create a NodeMailer transporter object to outline the service kind. SMTP is most typical, however others are available for different companies. An authentication consumer ID and password is normally vital:
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
host: 'smtp.yourserver.com',
port: 587,
auth: {
consumer: '[email protected]',
go: 'my-password'
},
});
You may ship emails to a number of recipients utilizing the transporter’s sendMail()
methodology:
const ship = await transporter.sendMail({
from: '"Take a look at Electronic mail" ' ,
to: '[email protected], [email protected]',
cc: '[email protected]',
bcc: '[email protected]',
topic: 'Hey!',
textual content: 'Plain textual content model of the message',
html: 'HTML model of the message
',
});
All e mail shoppers help plain textual content messages. You may also ship a rich-formatted model of the identical message used when the e-mail shopper helps HTML (extra about that below).
NodeMailer gives loads of other messaging options, however the commonest is attachments. An array of objects defines filenames and content material. For instance:
const ship = await transporter.sendMail({
attachments: [
{
filename: 'text1.txt',
path: '/path/to/file1.txt'
},
{
filename: 'text2.txt',
path: 'https://myserver.com/text2.txt'
},
{
filename: 'text3.txt',
content: 'This is the file content!'
},
{
filename: 'text4.txt',
path: 'data:text/plain;base64,SGVsbG8gd29ybGQh'
}
]
});
Sending Providers
It’s straightforward to ship easy one-off emails, however please don’t underestimate problem as your necessities evolve.
Chances are you’ll not have an SMTP server. Not all e mail companies present SMTP (Google is withdrawing basic SMTP support in Gmail).
Most companies restrict outgoing emails. Should you’re sending many emails, it’s possible you’ll hit your supplier’s restrict. At that time, all emails going by the identical service will fail: that’s your e-newsletter in addition to private and enterprise messages.
Chances are you’ll turn into a spammer. It’s straightforward for recipients to mark your e mail as “junk” — even when it’s not. When sufficient folks try this, you may uncover all emails out of your area turn into blocked throughout the Web.
It’s higher to make use of a devoted e mail service slightly than your personal mail server. The next companies cut back the potential issues and a few provide free plans for these with low utilization necessities:
Asynchronous software structure
Sending a single e mail is usually quick, however:
- the SMTP server may very well be down so retries are vital, or
- the message might get caught in the course of a bulk e-newsletter posting
Quite than sending emails straight inside your Node.js software, it’s usually higher to ship the info to a task queue. The tip consumer needn’t look ahead to a response and may proceed to make use of the app.
One other course of can monitor the e-mail queue, ship the subsequent message, and requeue objects when a failure happens.
Crafting HTML Emails
HTML5 and CSS3 work persistently nicely in trendy browsers. Electronic mail shoppers are one other matter, taking us again to the irritating late Nineteen Nineties days of tables and inline types.
These are a few of the points you’ll face:
There are dozens of native and web-based e mail shoppers together with Gmail, Yahoo Mail, Apple Mail, iOS Mail, Android Mail, Home windows Mail, Outlook, Outlook.com, (new) Outlook, Thunderbird, AOL, Claws, RoundCube, and so forth.
All use their very own strange rendering engines with distinctive points and bugs. Considerably bizarrely, Outlook has used Microsoft Phrase to render HTML since 2007 (though the brand new preview model is browser based mostly).
Most shoppers block or restrict fonts, photographs, trackers, media queries, iframes, movies, audio, varieties, and scripts.
Even web-based e mail shoppers working within the browser should take away HTML, CSS, and JavaScript that’s harmful or that might have an effect on UI structure. For instance, it shouldn’t be doable for an e mail to auto-click its personal hyperlinks or completely place a component over a delete button.
Electronic mail shoppers can reformat your HTML to make sure it’s a single column or adheres with the consumer’s mild/darkish mode preferences.
It’s doable to hand-code HTML emails however, except your structure is easy, it’s a troublesome, irritating, and error-prone. The next sections counsel instruments and sources that will make your life simpler.
Pre-built e mail templates
The next websites present free and business sturdy e mail templates you’ll be able to preview, obtain, and use with minimal effort:
Electronic mail template design instruments
The next no-code design instruments will let you create your personal HTML e mail templates utilizing an easier WYSWYG editor:
A few of these companies additionally present code validation and testing services.
Electronic mail template conversion
Premailer is an online instrument which takes a web page URL or pasted supply code and transforms it to email-compatible HTML and plain textual content templates. There’s a REST API and Node.js premailer-api
module ought to you have to automate the method.
Comparable instruments embrace:
Electronic mail template markup instruments
Cerberus, Email Framework, Email Skeleton, and Good Email Code present HTML part snippets you’ll be able to copy and adapt in your personal templates.
HEML and MJML are e mail markup languages. They’re much like HTML however stop typical compatibility points. Maizzle takes the same strategy utilizing Tailwind CSS.
Parcel is a code editor which understands e mail formatting and may present previews. You’ll additionally discover loads of email extensions for VS Code.
caniemail.com is the e-mail equal of the net web page caniuse.com and studies whether or not a selected HTML or CSS characteristic is usable throughout a number of shoppers. Lastly, Accessible Email gives related sources and hyperlinks.
Electronic mail testing instruments
Whereas an HTML e mail may go in your personal e mail apps, are you able to be certain it really works in others? The next instruments will assist, however there’s no substitute for testing a variety of actual gadgets, OSes, and e mail shoppers.
HTML Email Check and MailTrap validate your supply code and report issues you may encounter in particular shoppers.
emailpreview, Mailosaur, and Email Preview Services present structure preview services so you’ll be able to verify how your design will look on a wide range of shoppers.
Lastly, Litmus and Email on Acid have a variety of instruments to validate code, verify accessibility, preview throughout shoppers, report analytics, and run full advertising and marketing campaigns.
Learn to code emails the proper means
As we’ve seen above, there are various instruments that may provide help to to create e mail layouts that work throughout the numerous e mail shoppers on the market. However there’s nothing like understanding how one can code all by your self, particularly when you have to kind out the inevitable bugs that come up.
Should you’d prefer to be taught the ins and outs of e mail coding (even when it’s simply as a backup), try Crafting HTML Email, by Rémi Parmentier. It covers trendy views on constructing your personal e mail templates, important greatest practices, how one can add interactivity to emails, and how one can make your templates accessible. It even walks you thru a case examine to see all this in observe.
Studying Incoming Electronic mail
Most apps want solely ship emails, however there could also be events once you need to study incoming emails — for issues like service registration, unsubscribe dealing with, automated help, and so forth. Whereas it’s past the scope of this tutorial, Node.js modules similar to ImapFlow permit your software to connect with an IMAP inbox, fetch messages, and course of a response:
import ImapFlow from 'imapflow';
const shopper = new ImapFlow({
host: 'imap.e mail',
port: 993,
safe: true,
auth: {
consumer: '[email protected] mail',
go: 'mypassword'
}
});
strive {
await shopper.join();
const lock = await shopper.getMailboxLock('INBOX');
const msg = await shopper.fetchOne(shopper.mailbox.exists, { supply: true });
console.log( msg.supply.toString() );
lock.launch();
await shopper.logout();
}
catch (e) {
console.log(e);
}
Conclusion
Sending emails from Node.js internet apps is simple. Sending emails which look good, work reliably in all e mail shoppers, don’t halt the consumer, and don’t trigger spam woes will be significantly harder.
I like to recommend you retain emails easy to start out, maybe choosing rare plain textual content messages. In fact, your shoppers and advertising and marketing division will quickly need fancy colours and animations, however you’ll be able to ship that tomorrow!
Regularly Requested Questions (FAQs) about Sending Emails Utilizing Node.js
How can I connect recordsdata to my emails utilizing Node.js?
Attaching recordsdata to your emails utilizing Node.js is sort of simple. You should utilize the ‘attachments’ property within the mail choices. This property takes an array of attachment choices. Every attachment possibility is an object that incorporates the filename and path properties. The filename property is the identify of the file as it is going to seem within the e mail, and the trail property is the situation of the file in your system.
Right here’s an instance:
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
topic: 'Hey',
textual content: 'Hey world',
attachments: [
{
filename: 'file.txt',
path: '/path/to/file.txt'
}
]
};
Can I ship HTML emails utilizing Node.js?
Sure, you’ll be able to ship HTML emails utilizing Node.js. As an alternative of utilizing the ‘textual content’ property within the mail choices, you utilize the ‘html’ property. The worth of this property is the HTML content material of the e-mail.
Right here’s an instance:
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
topic: 'Hey',
html: ''
};
How can I ship emails to a number of recipients?
To ship emails to a number of recipients, you’ll be able to present an inventory of e mail addresses separated by commas within the ‘to’ property of the mail choices.
Right here’s an instance:
let mailOptions = {
from: '[email protected]',
to: '[email protected], [email protected]',
topic: 'Hey',
textual content: 'Hey world'
};
How can I deal with errors when sending emails?
You may deal with errors when sending emails by utilizing a callback operate. This operate is handed because the second argument to the ‘sendMail’ methodology. The callback operate takes two parameters: an error object and an information object. If an error happens when sending the e-mail, the error object will comprise details about the error.
Right here’s an instance:
transporter.sendMail(mailOptions, operate(error, information){
if (error) { console.log(error); } else {console.log('Electronic mail despatched: ' + information.response); } });
Can I take advantage of a Gmail account to ship emails?
Sure, you should use a Gmail account to ship emails. Nonetheless, you have to allow ‘Much less safe apps’ in your Gmail account settings. Additionally, you have to use ‘smtp.gmail.com’ because the host and 587 because the port within the transporter choices.
Right here’s an instance:
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
auth: {
consumer: '[email protected]',
go: 'your-password'
}
});
How can I ship emails asynchronously?
You may ship emails asynchronously by utilizing Guarantees. The ‘sendMail’ methodology returns a Promise that resolves with an information object when the e-mail is shipped.
Right here’s an instance:
transporter.sendMail(mailOptions)
.then(information => console.log('Electronic mail despatched: ' + information.response))
.catch(error => console.log(error));
Can I take advantage of a customized SMTP server to ship emails?
Sure, you should use a customized SMTP server to ship emails. You must present the host, port, and authentication particulars of the SMTP server within the transporter choices.
Right here’s an instance:
let transporter = nodemailer.createTransport({
host: 'smtp.instance.com',
port: 587,
auth: {
consumer: 'username',
go: 'password'
}
});
How can I ship emails with a selected charset?
You may ship emails with a selected charset by utilizing the ‘charset’ property within the mail choices. This property units the charset of the e-mail.
Right here’s an instance:
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
topic: 'Hey',
textual content: 'Hey world',
charset: 'UTF-8'
};
Can I ship emails with a selected content material kind?
Sure, you’ll be able to ship emails with a selected content material kind. You should utilize the ‘contentType’ property within the mail choices. This property units the content material kind of the e-mail.
Right here’s an instance:
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
topic: 'Hey',
textual content: 'Hey world'
contentType: 'textual content/plain
};
How can I ship emails with a selected encoding?
You may ship emails with a selected encoding by utilizing the ‘encoding’ property within the mail choices. This property units the encoding of the e-mail.
Right here’s an instance:
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
topic: 'Hey',
textual content: 'Hey world',
encoding: 'base64'
};