Site icon DataFlair

Nodemailer – Nodejs Send Email

nodemailer - nodejs send email

FREE Online Courses: Transform Your Career – Enroll for Free!

Almost every website nowadays requires sending of emails, so today we will be discussing various ways of sending emails in node js application. The most popular ways of sending mail are nodemailer with smtp, email api and multi channel notification service.

1. Nodejs Smtp:

Smtp stands for Simple Mail Transfer Protocol (SMTP). It is used for sending emails across networks and is the most popular transport method.

When we send email using Gmail, an outgoing (SMTP) server picks it and connects with the receiving server. The two servers communicate using guidelines defined by the SMTP protocol. It determines who is the recipient and how they will get the incoming mail.

Advantages of smtp:

Disadvantages of smtp:

Nodemailer with smtp:

It is the most popular node.js module which is used to send email. To install this module run npm install nodemailer.
To include this module use the require function eg:: let nodemailer=require(‘nodemailer’)

Send Email:

Nodemailer has a createTransport function that specifies the method we want to use. It takes connection data and credentials as an argument. We will need to define an SMTP host, port, and password for accessing the SMTP server.

For development purposes, we will use Mailtrap, to serve as a fake SMTP server.

Code for sending plain text email using nodemailer:

const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
    host: "smtp.mailtrap.io",
    port: 2525,
    auth: {
        user: "47d28bc0172bb8",
        pass: "45496c6e73505d"
    }
});
message = {
    from: "from-example@email.com",
    to: "to-example@email.com",
    subject: "Subject",
    text: "Hello SMTP Email"
}
transporter.sendMail(message, function (err, info) {
    if (err) {
        console.log(err)
    } else {
        console.log(info);
    }
})

Output

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

Replace the host, password and user using your mailtrap details and also replace the from and ‘to’ according to your need and that’s all just run the file the email id mentioned will receive an email.

2. Nodejs Transactional Email API:

It allows us to send email from our app using a hosted API. We can use the email API to handle sending and delivering the email. Transactional email APIs give a reliable service that can be used in our application easily with better functionality.

Advantages of transactional Email API:

Disadvantages of transactional Email Api:

Sending Email using Transactional Email API:

Some of the most popular platforms for sending mail using Transactional Email API are sendgrid and mailgun. In this article, we will be using sendgrid for sending email.

First, create an account in sendgrid (https://sendgrid.com/ ). Now go to sendgrid’s dashboard, then settings, then API key, to get the API key.

To install sendgrid run npm install –save @sendgrid/mail.

Include it in your file using the require function.

In the below code replace ‘SENDGRID_API_KEY’ with your SendGrid API key and replace the email address in the “from” by the email that you used in creating the sendgrid account, and also replace the “to” email address according to your need. Now you are ready to use sendgrid email service to send emails.

Code for sending email using sendgrid:

const sendgrid = require('@sendgrid/mail');
 
const SENDGRID_API_KEY = "<SENDGRID_API_KEY>"
 
sendgrid.setApiKey(SENDGRID_API_KEY)
 
const msg = {
    to: 'test@example.com',
    from: 'test@example.com',
    subject: 'Sending with SendGrid Is Fun',
    text: 'and easy to do anywhere, even with Node.js',
    html: '<strong>and easy to do anywhere, even with Node.js</strong>',
}
 
sendgrid
    .send(msg)
    .then((resp) => {
        console.log('Email sent\n', resp)
    })
    .catch((error) => {
        console.error(error)
    })

3. Nodejs Multichannel notification service:

Courier is the most common Multichannel notification service. It allows us to reach users from different channels using one API. It allows us to bring our own provider for each channel.

Advantages of Multichannel notification channel:

Disadvantages of Multichannel notification channel:

Sending email using Multichannel notification service:

First create an account on courier then install courier using npm as npm install @trycourier/courier.
In the below code replace event id, recipient id, and email with that of your courier data.

Code for sending email using courier client:

const { CourierClient } = require("@trycourier/courier");
 
const courier = CourierClient({ authorizationToken: "<AUTH_TOKEN>" });
 
courier.send({
    eventId: "<EVENT ID>",
    recipientId: "<RECIPIENT_ID",
    profile: {
        email: "<EMAIL_ADDRESS>"
    },
    data: {}
})
    .then((resp) => {
        console.log('Email sent', resp)
    })
    .catch((error) => {
        console.error(error)
    });

Sending HTML Email:

For sending html email you just have to change the text parameter in the message object to html and then use html in it.

Code for Sending a html Email:

const msg = {
    to: 'test@example.com',
    from: 'test@example.com',
    subject: 'Sending with SendGrid Is Fun',
    html: '<strong>DataFlair</strong>',
}

Sending Email with attachments:

For sending html email you just have to add an attachment parameter in the message object and then you can attach the file.

Code for sending email with attachments:

const msg = {
    to: 'test@example.com',
    from: 'test@example.com',
    subject: 'Sending with SendGrid Is Fun',
    html: '<strong>DataFlair</strong>',
attachments: [
        { 
          filename: 'DataFlair.jpg',
          path:’C:\Users\ASUS\DataFlair’ 
      }
    ]
}

Sending email to multiple receivers:

In order to send email to multiple people,add their email in the “to” parameter and use a comma to separate the emails.

Code for Sending a Email to multiple receiver:

const msg = {
    to: 'test@example.com',’test1@example.com’,
    from: 'test@example.com',
    subject: 'Sending with SendGrid Is Fun',
    html: '<strong>DataFlair</strong>',
}

Conclusion:

In this blog, we have explored different ways of sending email in a nodejs application. We have learned about smtp, nodemailer, sendgrid and courier. Hope you enjoyed reading the article.

Exit mobile version