473,545 Members | 2,009 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to Send an Email with Nodemailer

2 New Member
Nodemailer creators say that it makes sending an email a piece of cake. Let’s see if they are talking about cooking or eating 🙂 The idea of this article is to explain how to use Nodemailer for email sending. We will focus mainly on SMTP and HTML aspects but will also do an overview of all Nodemailer capabilities. Besides, this tutorial will help you prepare and test email messages to send out with your Node.js application.

How to use Nodemailer

Installation


The only thing required to start using Nodemailer is Node.js version 6.0 or above. You should also install Nodemailer itself but it’s really easy with the npm or Yarn package manager. Execute the following command in the Node.js command prompt:

Expand|Select|Wrap|Line Numbers
  1. npm install nodemailer
or
Expand|Select|Wrap|Line Numbers
  1. yarn add nodemailer
  2.  
Once completed, include it into your application like this:

Expand|Select|Wrap|Line Numbers
  1. var nodemailer = require('nodemailer');
or this if you are using ES modules:

Expand|Select|Wrap|Line Numbers
  1. import nodemailer from ‘nodemailer’;
Sending messages

To send a message with Nodemailer, there are three main steps.

Step 1. Create Nodemailer transporter

SMTP is the most common transporter, and below we will describe it in more detail, as well as demonstrate some examples. But there is a list of other available options:

- Built-in transports
- sendmail, a regular sendmail command for simple messages. It’s similar to the mail() function in PHP
- SES , to handle large traffic of emails by sending them using Amazon SES
- stream, a buffer for testing purposes, to return messages.

External transport. To put it simply, you can create your own transportation method.

For more details, refer to the Nodemailer documentation.

With SMTP, everything is pretty straightforward . Set host, port, authentication details and method, and that’s it. It’s also useful to verify that SMTP connection is correct at this stage: add verify(callback ) call to test connection and authentication.

Expand|Select|Wrap|Line Numbers
  1. transporter.verify(function(error, success) {
  2.    if (error) {
  3.         console.log(error);
  4.    } else {
  5.         console.log('Server is ready to take our messages');
  6.    }
  7. });
  8.  
How to test emails in Nodemailer?

To test emails sent with Nodemailer, we will use Mailtrap, an online tool for complex email testing in a pre-production environment. It will catch our messages, display how they look in a real email client, and help analyze and debug them. Mailtrap also provides Bcc testing options and allows you to share your email testing results with other team members, as well as forward emails to the real verified addresses.

Even If you don’t have an account yet, the whole set up process takes just a couple of minutes. Mailtrap integrates as a regular SMTP server. Quickly sign up (it’s free), go to the SMTP settings tab in your Inbox, copy the necessary settings, and insert them to your application script.

Mailtrap offers a ready-to-use integration with Nodemailer: select it from the Integrations section and insert it into your application code. It already contains transporter and syntaxis attributes:

Expand|Select|Wrap|Line Numbers
  1. var transport = nodemailer.createTransport({
  2.   host: "smtp.mailtrap.io",
  3.   port: 2525,
  4.   auth: {
  5.     user: "1a2b3c4d5e6f7g", //generated by Mailtrap
  6.     pass: "1a2b3c4d5e6f7g" //generated by Mailtrap
  7.   }
  8. });

Otherwise, you can use auto-generated email test accounts on Ethereal, which is also a fake SMTP service, mostly aimed at Nodemailer users.

Recently, Nodemailer has introduced NodemailerApp. It provides Sendmail replacement, but first of all, is designed to debug emails. NodemailerApp has SMTP and POP3 local servers, a catchall email domain service, along with email preview capabilities.

Step 2. Set Nodemailer message options

At this point, we should specify the sender, message recipients, and the content of our message.

Remember, Unicode is supported, so you can include emojis as well!

To send a text formatted as HTML, no extra attributes are required, just put your HTML body into the message with an html attribute. For advanced templates, you can add attachments and embed images. Let’s take a look at this example of simple message options first:

Expand|Select|Wrap|Line Numbers
  1. var mailOptions = {
  2.     from: '"Example Team" <from@example.com>',
  3.     to: 'user1@example.com, user2@example.com',
  4.     subject: 'Nice Nodemailer test',
  5.     text: 'Hey there, it’s our first message sent with Nodemailer ;) ',
  6.     html: '<b>Hey there! </b><br> This is our first message sent with Nodemailer'
  7. };
  8.  
Attachments in Nodemailer

You can add different types of data to your message in Nodemailer using the following main properties:

- filename: the name of the attached file. Here you can use Unicode as well.
- content: the body of your attachment. It can be a string, a buffer, or a stream.
- path: path to the file, to stream it instead of including it in the message. It is a good option for big attachments.
- href: attachment URL. Data URIs are also supported.

Expand|Select|Wrap|Line Numbers
  1. list: {
  2.             // List-Help: <mailto:admin@example.com?subject=help>
  3.             help: 'admin@example.com?subject=help',
  4.  
  5.             // List-Unsubscribe: <http://example.com> (Comment)
  6.             unsubscribe: [
  7.                 {
  8.                     url: 'http://example.com/unsubscribe',
  9.                     comment: 'A short note about this url'
  10.                 },
  11.                 'unsubscribe@example.com'
  12.             ],
  13.  
  14.             // List-ID: "comment" <example.com>
  15.             id: {
  16.                 url: 'mylist.example.com',
  17.                 comment: 'my new list'
  18.             }
  19.         }
  20.     };
Optional properties let you add specific content types or inline images.

contentType: if you don’t set it, it will be inferred from the filename property

Expand|Select|Wrap|Line Numbers
  1.  // An array of attachments
  2.         attachments: [
  3.             // String attachment
  4.             {
  5.                 filename: 'notes.txt',
  6.                 content: 'new important notes',
  7.                 contentType: 'text/plain' // optional, would be detected from the filename
  8.             },
CID: inline images in the HTML message. For more details on attaching images to HTML emails, read this post. Note that the CID value should be unique.

Expand|Select|Wrap|Line Numbers
  1. cid: 'note@example.com' // should be as unique as possible
  2.             },
  3.  
  4.             // File Stream attachment
  5.             {
  6.                 filename: 'matrix neo.gif',
  7.                 path: __dirname + '/assets/neo.gif',
  8.                 cid: 'neo@example.com' // should be as unique as possible
  9.             }
  10.         ],
Encoding: can be added to the string type of content. It will encode the content to a buffer type according to the encoding value you set (base64, binary, etc.)

Expand|Select|Wrap|Line Numbers
  1. // Binary Buffer attachment
  2.             {
  3.                 filename: 'image.png',
  4.                 content: Buffer.from(
  5.                     'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/' +
  6.                         '//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U' +
  7.                         'g9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC',
  8.                     'base64'
  9.                 )
Step 3. Deliver a message with sendMail()

Once we created a transporter and configured a message, we can send it using the _sendMail()_ method:

Expand|Select|Wrap|Line Numbers
  1. transport.sendMail(mailOptions, (error, info) => {
  2.         if (error) {
  3.             return console.log(error);
  4.         }
  5.         console.log('Message sent: %s', info.messageId);
  6. });
Nodemailer capabilities

We have covered the info on how to create and send an email in Nodemailer via SMTP, experimenting with different types of content: HTML, tables, lists, attachments, and embedded images.What is good about Nodemailer is that it offers a bunch of various options and settings, so you can customize every piece of your email.
Apr 11 '22 #1
2 7493
webapp
2 New Member
Expand|Select|Wrap|Line Numbers
  1. const nodemailer = require('nodemailer');
  2.  
  3.  
  4. let mailTransporter = nodemailer.createTransport({
  5.     service: 'gmail',
  6.     auth: {
  7.         user: 'xyz@gmail.com',
  8.         pass: '*************'
  9.     }
  10. });
  11.  
  12. let mailDetails = {
  13.     from: 'xyz@gmail.com',
  14.     to: 'abc@gmail.com',
  15.     subject: 'Test mail',
  16.     text: 'Node.js testing mail for GeeksforGeeks'
  17. };
  18.  
  19. mailTransporter.sendMail(mailDetails, function(err, data) {
  20.     if(err) {
  21.         console.log('Error Occurs');
  22.     } else {
  23.         console.log('Email sent successfully');
  24.     }
  25. });
Apr 12 '22 #2
puananiila99
1 New Member
options – It is an object that is used to connect with any host.
defaults – It is an object combining into each message object. ...
port – if secure is false, it uses 587, by default, and 465 if true. ...
from – Sender's email address. ...
subject – Email's subject.
Apr 13 '22 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

3
9521
by: Salim Afþar | last post by:
Hi, I'm using CDO object to send email but it doesn't send any email and it does not give an error. My code look like this: Dim iMsg2 Dim iConf2 Dim Flds2 Const cdoSendUsingPort = 2 set iMsg2 = CreateObject("CDO.Message")
1
5325
by: Jay McGrath | last post by:
Help - trying to send a simple text email with with as little user intervention. I am trying to create a button in my Access application that will automatically send a simple text email. It works except that I have two warning nuisances: 1) Program is trying to access email Addresses you have stored in Outlook. Allow access for ... 2) A...
9
4295
by: Bob Jones | last post by:
We have developed a commercial ASP.net application (personal nutrition management and tracking); we want to send smtp email from within it. For our development box, we use WinXP Pro, IIS 5.5, VisualStudio2002, VB as programing language. Our test/development version of the web app as hosted on our "localhost" works fine; our "Default SMTP...
2
2331
by: Ron | last post by:
hi guys, I am trying to send email using smtpMail. I can send emails inside the organization, but out of the organization I get an error "The server rejected one or more recipient addresses. The server response was: 550 5.7.1 Unable to relay for ........" now I tried to add username and password for the server to relay but it is still not...
3
4541
by: Gerard | last post by:
Hello I have created a windows service to monitor a database, it starts some checks when a timer elapses. The checks send emails depending on their findings. My issue is that when I created a windows application it worked fine, however I need to use a service as I don't want to rely on a user being logged in. The errors I get are: Index...
2
336
by: ucasesoftware | last post by:
i start a process to send email via Outlook I have succes to build the email text, objet, sender... but i want to automate the "send"... i don't want my users to click on Send email button... is it possible ?
3
9733
by: =?Utf-8?B?SHVnaA==?= | last post by:
Hi There, I use follow code to send email inside VB.NET 2005. It does not work well. Error message of "Failure sending email" would occue. However, email was sent out sometimes. I am confused and please help. Thanks in advance. Hugh
16
4709
by: =?Utf-8?B?Q2hlZg==?= | last post by:
I can use outlook2003 to send email,but I cann't use this code below to send email. Please help me to test this code and instruct me how to solve this problem in detail. software environment: VS2005 + XP.-- I have disabled firewall hardware enviornmnet:telcom's modem connects hub,hub connects two computers.。-- I also tried to...
0
1727
by: Mike Massaro | last post by:
Hello everyone, I'm new to PHP and creating an advertising website for massage therapists. On the profile page I'm creating a button so anyone can click on to send the advertiser an email. I created a page called profile_sendemail.php which contains the form to send the email and here is the code: <?php // Start_session, check if user is...
1
2996
by: prita1001 | last post by:
previously i am trying to send mails in separate form like this http://i.stack.imgur.com/klLVx.png but now i want to send mail automatically in respective email address.. Admin approve/reject documents now i want to add when admin approve/reject any documents then respective document name and the value which admin select (like approve...
0
7664
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7921
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7437
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7771
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5343
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4958
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3465
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1023
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.