How to Send Emails in Node.js

Written by cigargalaxy82 | Published 2022/12/06
Tech Story Tags: nodejs | email | api | programming | emails-in-node.js | nodejs-developer | nodejs-tutorial | nodejs-apps

TLDRIn this article, we will learn how to send emails in node.js. We are going to use Superface.ai for API integration as it makes the integration super easy. You can use many providers using the same interface and use more ready-made API use cases from the Superface catalog. SendGrid.ai is one of the most important forms of communication today and sending emails is a crucial form of communication. To send emails to Cedes, send an email to him: "Cedes, your recent order on Our Shop has been shipped"via the TL;DR App

In this article, we will learn how to send emails in node.js. We all receive email on daily basis, and it is one of the most crucial forms of communication today so knowing how to send one using node.js is quite awesome and useful

Introduction to Superface.ai

I am going to use Superface for API integration as it makes the integration super easy. I don’t have to deal with API docs, and I can use many providers using the same interface. Furthermore, I can use more ready-made API use cases from Superface catalogLearn one to conquer all.

Create a Node.js Project

mkdir sendEmail
cd sendEmail
npm init -y

Installing Superface SDK

npm i @superfaceai/one-sdk

Then choose your use case. We are going to use Send Email | Superface.

Now you have to configure the provider you want to use I am going with SendGrid. First, create your account get your api key and verify Single Sender Verification

I am using https://emailfake.com/ to get some temporary emails.

Back in Superface, copy and paste the code from the example and replace the token with your key.

const { SuperfaceClient } = require('@superfaceai/one-sdk');

const sdk = new SuperfaceClient();

export default async function run(req,res) {

   const profile = await sdk.getProfile('communication/send-email@2.1.0')
  // Use the profile
  const result = await profile
    .getUseCase('SendEmail')
    .perform({
    from: 'cedesdxesxd@24mail.top',
        to: 'cedesdxesxd@omdiaco.com',
        subject: 'Your order has been shipped!',
        text: 'Hello Cedes, your recent order on Our Shop has been shipped.',
    }, {
      provider: 'sendgrid',
      security: {
        bearer_token: {
          token: '<your token from sendgrid>'
        }
      }
    });

  try {
    const data = result.unwrap();
    res.send(data)
  } catch (error) {
    console.error(error);
  }
}

run()

Now to check if everything works, run the application:

node index.js

We can see the email is received.

You can also send attachments like pdf files and more.

To learn how to send email in Node.js —Sending Emails with Node.js using Superface.ai — YouTube


Also Published Here


Written by cigargalaxy82 | Developer looking to learn new things
Published by HackerNoon on 2022/12/06