Sending emails is a vital feature for several application use-cases. We use emails to communicate with the end-users of our application, send notifications and assist in signup or login processes. In this post, we will learn how to implement Fastify send email feature using Nodemailer and fastify-mailer packages.

Nodemailer and fastify-mailer are packages that make the task of sending emails easy. All we have to do is configure the usage of these packages.

If you are new to Fastify, I will recommend you to go through the basics of Fastify.

1 – Installation of Fastify Send Email Packages

The first step is to install the necessary packages.

See the below command:

$ npm install fastify-mailer nodemailer --save

Basically, we install fastify-mailer and nodemailer packages. Also, note that the fastify-mailer package will make use of the nodemailer package.

2 – Configuring the fastify-mailer package

Once the installation is complete, we need to configure the fastify-mailer package to enable Fastify send email feature for our application.

See below example:

const fastify = require('fastify')({ logger: true })

fastify.register(require('fastify-mailer'), {
  defaults: { from: ' <noreply@example.com>' },
  transport: {
    host: 'smtp.sendgrid.net',
    secure: false, 
    auth: {
      user: apikey,
      pass: <YOUR_SENDGRID_API_KEY>
    }
  }
})

We first create a Fastify instance. Next, we have to register the fastify-mailer plugin using the register() API. If you want to read more about plugins, check out this detailed post on Fastify plugin system.

For this example, I am assuming you are using a mail provider such as Sendgrid. Therefore, the value of host parameter is smtp.sendgrid.net.

Next, for the critical authorization parts, we have user value as apikey and the password as the Sendgrid API Key. You can obtain an API key by creating an account on Sendgrid.

However, if you are using some other provider, you have to change the values accordingly. Also, please don’t place the API keys in the source code and commit the same to a source code repository.

For a real production application, it is advisable to keep credentials and API keys in separate environment files. You can also use an environment file with Fastify. Check out this post on Fastify Env Setup.

3 – Fastify Send Email Endpoint

Now that the configuration is done, it is time to implement the email sending logic.

To do so, we basically create an endpoint that can be triggered by a REST call. However, this approach is not necessary. Email can be sent based on various triggers generated by your application.

See below:

fastify.get('/email', (request, reply) => {
  const { mailer } = fastify

  mailer.sendMail({
    to: 'test@gmail.com',
    subject: 'Test Email',
    text: 'Hello, World Email !'
  }, (errors, info) => {
    if (errors) {
      fastify.log.error(errors)

      reply.status(500)
      return {
        status: 'error',
        message: 'There is some error'
      }
    }

    reply.status(200)
    return {
      status: 'ok',
      message: 'Email successfully sent',
      info: {
        from: info.from,
        to: info.to,
      }
    }
  })
})

As you can see, here we are simply extracting the mailer module from the fastify context. Then, we call the mailer.sendMail() function. Basically, this function takes an object as input containing all the details about the recipient and the actual email message.

If everything goes fine, the email is send to the recipient. Else, Fastify will log the error messages and return the error response to the client.

4 – Conclusion

Fastify send email using fastify-mailer and Nodemailer combination is a hassle free way to handle emails functionality. The main thing is to place the proper configuration parameters.

If you are interested in learning more of Fastify, check out this post on building a Fastify REST API from scratch using Postgres and Swagger.

Categories: BlogFastify

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *