Sending Emails with MailerSend and Node.js

MailerSend provides a Node SDK that you can use to send emails from your Node.js applications. This guide will walk you through the steps required to set up a sample Node.js app that uses the MailerSend SDK to send emails.

Prerequisites

Before you get started, you'll need to have the following:

  • A MailerSend account
  • A MailerSend API key
  • Node.js and npm installed on your machine

Install the MailerSend SDK

First, you'll need to install the MailerSend SDK. Open your terminal and navigate to your project directory. Then, run the following command:

npm install mailersend dotenv

This will install the MailerSend SDK and dotenv module and their dependencies in your project.

Set Up Your Environment Variables

Next, you'll need to set up your environment variables. Create a new file named .env in your project directory and add the following lines:

MAILERSEND_API_KEY=<your_api_key>

Replace <your_api_key> with your actual MailerSend API key.

Create Your Node.js App

Now, you're ready to create your Node.js app. Create a new file named app.js in your project directory and add the following code:

import 'dotenv/config';
import { MailerSend, EmailParams, Sender, Recipient } from "mailersend";

const mailerSend = new MailerSend({
  apiKey: process.env.API_KEY,
});

const sentFrom = new Sender("bbbb@yourdomain.com", "Your name");

const recipients = [
  new Recipient("your@client.com", "Your Client")
];
const cc = [
  new Recipient("your_cc@client.com", "Your Client CC")
];
const bcc = [
  new Recipient("your_bcc@client.com", "Your Client BCC")
];

const emailParams = new EmailParams()
  .setFrom(sentFrom)
  .setTo(recipients)
  .setCc(cc)
  .setBcc(bcc)
  .setSubject("This is a Subject")
  .setHtml("<strong>This is the HTML content</strong>")
  .setText("This is the text content");

mailerSend.email
	.send(emailParams)
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

This code initializes the MailerSend SDK with your API key, creates an email object with the necessary details (such as the recipient's email address, the sender's email address, the email subject, and the HTML body), and sends the email using the email module mailerSend.email.send() method.

Run Your Node.js App

Finally, you're ready to run your Node.js app. Open your terminal, navigate to your project directory, and run the following command:

node app.js

This will run your app and send the email. You should see a successful response in your terminal if everything is set up correctly.

Conclusion

In this guide, you learned how to set up a Node.js app to send emails using the MailerSend SDK. By following these steps, you can quickly integrate MailerSend into your Node.js app and start sending emails.

What’s next?

Last Updated: