npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

fastify-mailer

v2.3.1

Published

Nodemailer instance initialization and encapsulation in fastify framework

Downloads

2,996

Readme

fastify-mailer

NPM version GitHub CI Coverage Status js-standard-style

Nodemailer instance initialization and encapsulation in fastify framework.

Install

Install the package with:

npm i fastify-mailer nodemailer --save

Usage

The package needs to be added to your project with register and you must at least configure your transporter options following Nodemailer documentation and you are done.

'use strict'

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

fastify.register(require('fastify-mailer'), {
  defaults: { from: 'John Doe <[email protected]>' },
  transport: {
    host: 'smtp.example.tld',
    port: 465,
    secure: true, // use TLS
    auth: {
      user: 'john.doe',
      pass: 'super strong password'
    }
  }
})

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

  mailer.sendMail({
    to: '[email protected]',
    subject: 'example',
    text: 'hello world !'
  }, (errors, info) => {
    if (errors) {
      fastify.log.error(errors)

      reply.status(500)
      return {
        status: 'error',
        message: 'Something went wrong'
      }
    }

    reply.status(200)
    return {
      status: 'ok',
      message: 'Email successfully sent',
      info: {
        from: info.from, // John Doe <[email protected]>
        to: info.to, // ['[email protected]']
      }
    }
  })
})

fastify.listen(3000, (errors) => {
  if (errors) {
    fastify.log.error(errors)
    process.exit(1)
  }
})

Options

  • defaults: is an optional object that defines default values for mail options.

example:

'use strict'

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

fastify.register(require('fastify-mailer'), {
  defaults: {
    // set the default sender email address to [email protected]
    from: 'Jane Doe <[email protected]>',
    // set the default email subject to 'default example'
    subject: 'default example',
  },
  transport: {
    host: 'smtp.example.tld',
    port: 465,
    secure: true, // use TLS
    auth: {
      user: 'jane.doe',
      pass: 'super strong password'
    }
  }
})

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

  mailer.sendMail({
    to: '[email protected]',
    text: 'hello world !'
  }, (errors, info) => {
    if (errors) {
      fastify.log.error(errors)

      reply.status(500)
      return {
        status: 'error',
        message: 'Something went wrong'
      }
    }

    reply.status(200)
    return {
      status: 'ok',
      message: 'Email successfully sent',
      info: {
        from: info.from, // Jane Doe <[email protected]>
        to: info.to, // ['[email protected]']
      }
    }
  })
})

fastify.listen(3000, (errors) => {
  if (errors) {
    fastify.log.error(errors)
    process.exit(1)
  }
})
  • namespace: is an optional string that lets you define multiple namespaced transporter instances (with different options parameters if you wish) that you can later use in your application.

example:

'use strict'

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

fastify
  .register(require('fastify-mailer'), {
    defaults: {
      // set the default sender email address to [email protected]
      from: 'Jane Doe <[email protected]>',
      // set the default email subject to 'default example'
      subject: 'default example',
    },
    namespace: 'jane',
    transport: {
      host: 'smtp.example.tld',
      port: 465,
      secure: true, // use TLS
      auth: {
        user: 'jane.doe',
        pass: 'super strong password for jane'
      }
    }
  })
  .register(require('fastify-mailer'), {
    defaults: { from: 'John Doe <[email protected]>' },
    namespace: 'john',
    transport: {
      pool: true,
      host: 'smtp.example.tld',
      port: 587,
      secure: false,
      auth: {
        user: 'john.doe',
        pass: 'super strong password for john'
      }
    }
  })

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

  mailer.jane.sendMail({
    to: '[email protected]',
    text: 'hello world !'
  }, (errors, info) => {
    if (errors) {
      fastify.log.error(errors)

      reply.status(500)
      return {
        status: 'error',
        message: 'Something went wrong'
      }
    }

    reply.status(200)
    return {
      status: 'ok',
      message: 'Email successfully sent',
      info: {
        from: info.from, // Jane Doe <[email protected]>
        to: info.to, // ['[email protected]']
      }
    }
  })
})


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

  mailer.john.sendMail({
    to: '[email protected]',
    subject: 'example with john',
    text: 'hello world !'
  }, (errors, info) => {
    if (errors) {
      fastify.log.error(errors)

      reply.status(500)
      return {
        status: 'error',
        message: 'Something went wrong'
      }
    }

    reply.status(200)
    return {
      status: 'ok',
      message: 'Email successfully sent',
      info: {
        from: info.from, // John Doe <[email protected]>
        to: info.to, // ['[email protected]']
      }
    }
  })
})

fastify.listen(3000, (errors) => {
  if (errors) {
    fastify.log.error(errors)
    process.exit(1)
  }
})
  • transport: is a required transport configuration object, connection url or a transport plugin instance.

example using SES transport:

'use strict'

const fastify = require('fastify')({ logger: true })
const aws = require('@aws-sdk/client-ses')

/**
 * configure AWS SDK:
 *
 * Use environment variables or Secrets as a Service solutions
 * to store your secrets.
 *
 * NB: do not hardcode your secrets !
 */
process.env.AWS_ACCESS_KEY_ID = 'aws_access_key_id_here'
process.env.AWS_SECRET_ACCESS_KEY = 'aws_secret_access_key_here'

const ses = new aws.SES({
  apiVersion: '2010-12-01',
  region: 'us-east-1'
})

fastify.register(require('fastify-mailer'), {
  defaults: { from: 'John Doe <[email protected]>' },
  transport: {
    SES: { ses, aws }
  }
})

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

  mailer.sendMail({
    to: '[email protected]',
    subject: 'example',
    text: 'hello world !',
    ses: {
      // optional extra arguments for SendRawEmail
      Tags: [
        {
          Name: 'foo',
          Value: 'bar'
        }
      ]
    }
  }, (errors, info) => {
    if (errors) {
      fastify.log.error(errors)

      reply.status(500)
      return {
        status: 'error',
        message: 'Something went wrong'
      }
    }

    reply.status(200)
    return {
      status: 'ok',
      message: 'Email successfully sent',
      info: {
        envelope: info.envelope, // {"from":"John Doe <[email protected]>","to":['[email protected]']}
      }
    }
  })
})

fastify.listen(3000, (errors) => {
  if (errors) {
    fastify.log.error(errors)
    process.exit(1)
  }
})

For more information on transports you can take a look at Nodemailer dedicated documentation.

Typescript users

Types for nodemailer are not officially supported by its author Andris Reinman.

If you want to use the DefinitelyTyped community maintained types:

  • first you need to install the package with :
npm install -D @types/nodemailer
  • then you must re-declare the mailer interface in the fastify module within your own code to add the properties you expect.

example :

import { Transporter } from "nodemailer";

export interface FastifyMailerNamedInstance {
  [namespace: string]: Transporter;
}
export type FastifyMailer = FastifyMailerNamedInstance & Transporter;

declare module "fastify" {
  interface FastifyInstance {
    mailer: FastifyMailer;
  }
}

Documentation

See Nodemailer documentation.

Acknowledgements

This project is kindly sponsored by coopflow.

License

Licensed under MIT