Giter Site home page Giter Site logo

fastify-mailer's Introduction

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

fastify-mailer's People

Contributors

coopflow avatar dependabot[bot] avatar greenkeeper[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

lgs yusuf-khamis

fastify-mailer's Issues

Question: ES6 import syntax

I'm try this plugin and I use ES6.
if I do:
import * as zio from 'fastify-mailer'
or
import { fastifyMailer } from 'fastify-mailer'
or
import zio from 'fastify-mailer'

I get:

Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)
// ...
{                                                                                                                                                                   
2:     "name": "nodemailer",                                                                                                                                           
             ^                                                                                                                                                         
3:     "version": "6.6.1",      

the error seams on nodemailer but is due to my try to use import for fastify-mailer.
if I use require(), all go well.

Someone know the right ES6 syntax for import this plugin?

best regards,
Leonardo

P.S.
reading manual is not help me.

Hi, Does it's work with google OAuth2?

Hi, How I can make this work?

I did not find the way to do in OAuth2 :)

This code is from my last server with express

const transport = nodemailer.createTransport({
         service:'gmail',
         auth: {
             type: 'OAuth2',
             user: process.env.USER, 
     
             clientId: process.env.CLIENT_ID,
             clientSecret: process.env.CLIENT_SECRET ,
             refreshToken: process.env.REFRESH_TOKEN,
             accessToken: process.env.ACCESS_TOKEN
         }
       });
       
       transport.use('compile', hbs({
         viewEngine: 'express-handlebars', //TEST
         viewPath: './views/'
       }));
       nodemailer.sendMail({mail_options}, (err, info) => {
         if (err){
          reply.code(500).send({ 
            success:false,
            data: 'Une erreur sait produite lors de l\'envoie du mail...!'
        })
       

Thank

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.