How to Send Emails In Node

How to Send Emails In Node

Integrate Mailjet into your Express app
Ferenc AlmasiLast updated 2021 November 11 • Read time 7 min read
Get your weekly dose of webtips
  • twitter
  • facebook

Recently I wrote an article about how I make my CSS more readable in HTML emails with the help of JavaScript. Today I would like to continue with a tutorial on how you can actually send out those emails in Node with the help of Mailjet.

By the end of this tutorial, you should have a better understanding of how to integrate Mailjet into your Express app as well as what steps you need to take to make sure you avoid landing in the spam folder.


Why Did I Choose Mailjet?

I was looking through a list of free services I could use that has an easy-to-use API that can be integrated into an Express app. I also needed a trusted service that could ensure that my mails won’t end up in the spam folder. Having analytics and statistics would also have been an added plus but not a requirement. I eventually stumbled upon Mailjet which happened to have everything.

This tutorial aims to help you set up your own implementation in JavaScript with the intent to provide you with a basic step-by-step guide.


Pre-requirements

For this tutorial, you’ll need to have an express REST API set up. We are going to use a post request to a route to trigger sending emails. If you would like to learn more about how to set up a REST API in Express, I have a tutorial that covers the topic in detail with code examples and images. You can reach it at the provided link.

In Express

We will also need to npm i node-mailjet which exposes the API used to interact with Mailjet. Make sure you have version 3 or above in your package.json file.

Copied to clipboard!
{
    ...
    "dependencies": {
        ...
        "node-mailjet": "3.3.1"
    }
}
package.json

In Mailjet

You’ll also going to need a Mailjet account. Once you’ve registered, you will be provided with a public and private API keys which can be used to send requests to the Mailjet API. We’re going to use these to trigger sending emails from our app. You can always retrieve your API keys under the “API Key Management” tab.

Adding sender and getting API key

But first, add your address which you want to use to send out emails from. The type may differ for your case. In this tutorial, we are using the service to send password recovery emails only to one recipient. So I’m going with transaction, the very first type:

Type of email address
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Integrating Mailjet

With that being said, we can start looking into how to send out emails. First, you’ll need to import node-mailet and provide the public and private keys that have been generated for your account:

Copied to clipboard!
const mailjet = require('node-mailjet').connect(process.env.MAILJET_PUBLIC_KEY, process.env.MAILJET_PRIVATE_KEY);
Route.js

You can either add them directly here or as I did in the example above, you can provide it as process.env variables. This has a couple of advantages:

  • First, it’s going to ensure that sensitive data cannot be seen from the source code.
  • It also allows developers to confidently debug and tackle any issue since you can provide fake keys locally which prevents sending out emails accidentally.

The real keys can be provided through CI once your application has been built and deployed. The next step is to create a send and request object which will hold information about the mail:

Copied to clipboard! Playground
post(request, response) {
    const i18n = require('../i18n/' + (request.body.locale || 'en'));
    const send = mailjet.post('send');
    const requestObject = { Messages:[{
        From: {
            Email: '[email protected]',
            Name: 'Ferenc Almasi'
        },
        To: [{
            Email: request.body.email
        }],
        Subject: i18n.passwordResetMailSubject,
        HTMLPart: passwordResetTemplate(i18n)
    }]};
}
Route.js

You can also see I’ve imported an i18n object. This only holds strings. Therefore, based on the provided locale param in the request body, we can generate different HTML templates for different languages.

Creating a send object is as simple as calling mailjet.post with the first parameter being “send”. This creates a POST httpRequest. The parameter provided is the Mailjet API function that will be used.

Next, we have the requestObject. This is made up of Messages, an array of objects so you can send out multiple mails at once. The absolute necessary and most important parts are the From and To objects alongside with the Subject and HTMLPart. The parameter To is also an array so you can specify more than one recipient. We need to point out that the To email is referencing request.body.email. This way, we can specify where we want to send the email in the request body, alongside with the locale.

Also If you are only going to send out plain text, you can use TextPart instead of HTMLPart. And where is the template coming from? This is just a function which exports a string of HTML with some embed text. This is why the i18n object has been passed into it. If you would like to peek inside the function, there’s a tutorial I’ve written about my approach to readable CSS in HTML templates.

But this is so far the configuration. We haven’t really told Express to send out the mail. So let’s extend the code example above with the following lines:

Copied to clipboard! Playground
post(request, response) {
    ...
    send.request(requestObject).then(() => {
        response.json({
            success: true
        });
    }).catch((err) => {
        console.log(err);

        response.json({
            error: err.statusCode
        });
    });
}
Route.js

We call request on the send object passing in the requestObject we’ve just created. If everything worked fine, we should land in the then clause and return with a successful JSON response. Otherwise, we simply log out the error to the console and return with the error code which can give us a clue about what went wrong.

Testing out Mailjet in Postman
I’m testing out my changes in Postman

I’ve provided both an email and a locale into request.body and then I hit send. First, we get back an error with an error code of 401. If we look into the console we can indeed see that we are not authorized to use the API. This is because the public and private API keys which we provided as process.env variables are undefined. After I change them to their real value, the issue is resolved.


Additional Tips

That’s all there is to it. However, we’re not quite done yet. We’ve managed to send out emails without issues, but they are all landing in the spam folder. Why is that happening?

Your mails are holding various meta-information about its sender which determines its trustworthiness. Clients will see that the domain that belongs to the sender’s email address will differ from the server (Mailjet).

To improve deliverability, it is strongly recommended to set up some DNS records, namely SPF and a DomainKey:

  • SPF determines which servers are allowed to send out emails from your domain
  • While the DomainKey Identified Mail record or DKIM for short will hold a public key which is used to verify if the email comes from an authorized sender.

Go to your dashboard and head over to your account and click on the “Setup SPF/DKIM Authentication” option.

Location of SPF/DKIM authentication

Setup may differ for your domain but the necessary records will be provided for you to copy into your DNS settings.

This will improve the reputation of your mails and can help you avoid landing in the spam folder. It may take some time for Mailjet to confirm your SPF and DKIM but once it’s done, you should be all good to start sending out emails to your customers.

Setup SPF and DomainKey to avoid landing in spam

If you ever need additional details on how to use the API, I can recommend the official developers documentation which has many examples not just for Node but for PHP, Python, Java, and a couple of other languages. Thank you for reading through and happy email sending. 📧

Try out mailjet for free
  • twitter
  • facebook
Did you find this page helpful?
📚 More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.