How to send emails from Node.js with SendInBlue in Cules Coding by @thatanjan

How to send emails from Node.js with SendInBlue

In this article, we will learn how to send emails from Node.js with SendInBlue.

Video Tutorial

What is SendInBlue?

SendInBlue is a mail service that allows you to send emails from your Node.js application.

Get Sendinblue email api key

  1. Go to SendinBlue and create an account.

  2. Go to Dashboard and click on the top right-hand side dropdown.

  3. Click on the SMTP & API tab.

  4. Click on the Create new API key button.

  5. Now we need to store the api key in an environment variable.

Setup

  • Install packages:
1npm init -y
2npm i dotenv sib-api-v3-sdk
  • Create a file called .env and add the following lines:
1API_KEY=<your_api_key>
  • Create a file called index.js and add the following lines:
1const Sib = require('sib-api-v3-sdk')
2
3require('dotenv').config()
4
5const client = Sib.ApiClient.instance
6
7const apiKey = client.authentications['api-key']
8apiKey.apiKey = process.env.API_KEY

Explanation: - require('dotenv').config(): This is used to load the environment variables from the .env file. Then we have to add the api key to the Sendinblue client.

1const tranEmailApi = new Sib.TransactionalEmailsApi()
2
3const sender = {
4 email: 'thatanjan@gmail.com',
5 name: 'Anjan',
6}
7
8const receivers = [
9 {
10 email: '<email address>',
11 },
12]

Explanation: With tranEmailApi we can send emails. The sender email has to be the email account that you have used in the SendinBlue account.

1tranEmailApi
2 .sendTransacEmail({
3 sender,
4 to: receivers,
5 subject: 'Subscribe to Cules Coding to become a developer',
6 textContent: `
7 Cules Coding will teach you how to become {{params.role}} a developer.
8 `,
9 htmlContent: `
10 <h1>Cules Coding</h1>
11 <a href="https://cules-coding.vercel.app/">Visit</a>
12 `,
13 params: {
14 role: 'Frontend',
15 },
16 })
17 .then(console.log)
18 .catch(console.log)

Explanation:

  • You can send emails using the sendTransacEmail method.

  • Subject is required.

  • You have to pass either textContent or htmlContent to the method. htmlContent will override textContent.

  • You can pass parameters to the email content using the params object.

  • Run the file and you will see the email was sent.

1node index.js

Sendinblue has templates that you can use. If you want me to teach you how to create a newsletter, please let me know.

Shameless Plug

I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Previous PostHow to Setup and Structure Your GraphQL Project
Next PostSetup NodeJS with babel for production