Git Product home page Git Product logo

yanarp / nestjs-mailer Goto Github PK

View Code? Open in Web Editor NEW
119.0 4.0 31.0 1.19 MB

๐ŸŒˆ A simple implementation example with and without email-templates using mailer module for nest js built on top of nodemailer.

Home Page: https://github.com/nest-modules/mailer

License: MIT License

JavaScript 3.36% TypeScript 23.80% Handlebars 72.84%
nestjs nestjsmailer nodemailer smtp outlook nestjs-mailer kit sender ejs handlebars

nestjs-mailer's Introduction

Nest Logo

Demo implementation on the mailer modules for Nest framework (node.js) using Nodemailer library

Nestjs-mailer starter kit / project for your NestJs project.

Goals

The main goal of this kit is to quickly get you started on your project with Nestjs Mailer, bringing a solid layout foundation to work upon.

Usage

Import the MailerModule into the root AppModule

Synchronous import

//app.module.ts
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';  
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';

@Module({
  imports: [
    MailerModule.forRoot({
      transport: {
        host: 'smtp.example.com',
        port: 587,
        secure: false, // upgrade later with STARTTLS
        auth: {
          user: "username",
          pass: "password",
        },
      },
      defaults: {
        from:'"nest-modules" <[email protected]>',
      },
      template: {
        dir: process.cwd() + '/templates/',
        adapter: new HandlebarsAdapter(), // or new PugAdapter()
        options: {
          strict: true,
        },
      },
    }),
  ],
})
export class AppModule {}

Asynchronous import

//app.module.ts
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';  
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';

@Module({
  imports: [
    MailerModule.forRootAsync({
      useFactory: () => ({
        transport: {
          host: 'smtp.example.com',
          port: 587,
          secure: false, // upgrade later with STARTTLS
          auth: {
            user: "username",
            pass: "password",
          },
        },
        defaults: {
          from:'"nest-modules" <[email protected]>',
        },
        template: {
          dir: process.cwd() + '/templates/',
          adapter: new HandlebarsAdapter(), // or new PugAdapter() or new EjsAdapter()
          options: {
            strict: true,
          },
        },
      }),
    }),
  ],
})
export class AppModule {}
  • We have used Handlebars in above example, for EJS and Pug use below mentioned example of adapter import

Pug

//app.module.ts
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';  
import { PugAdapter } from '@nestjs-modules/mailer/dist/adapters/pug.adapter';

EJS

//app.module.ts
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';  
import { EjsAdapter } from '@nestjs-modules/mailer/dist/adapters/ejs.adapter';

After this, MailerService will be available to inject across entire project, for example in this way :

import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';

@Injectable()
export class ExampleService {
  constructor(private readonly mailerService: MailerService) {}
}

MailerProvider exports the sendMail() function to which you can pass the message options (sender, email subject, recipient, body content, etc)

sendMail() accepts the same fields as nodemailer email message

import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';

@Injectable()
export class ExampleService {
  constructor(private readonly mailerService: MailerService) {}
  
  public example(): void {
    this
      .mailerService
      .sendMail({
        to: '[email protected]', // list of receivers
        from: '[email protected]', // sender address
        subject: 'Testing Nest MailerModule โœ”', // Subject line
        text: 'welcome', // plaintext body
        html: '<b>welcome</b>', // HTML body content
      })
      .then((success) => {
        console.log(success)
      })
      .catch((err) => {
        console.log(err)
      });
  }
  
  public example2(): void {
    this
      .mailerService
      .sendMail({
        to: '[email protected]',
        from: '[email protected]',
        subject: 'Testing Nest Mailermodule with template โœ”',
        template: 'index', // The `.pug` or `.hbs` extension is appended automatically.
        context: {  // Data to be sent to template engine.
          code: 'cf1a3f828287',
          username: 'john doe',
        },
      })
       .then((success) => {
        console.log(success)
      })
      .catch((err) => {
        console.log(err)
      });
  }
  
  public example3(): void {
    this
      .mailerService
      .sendMail({
        to: '[email protected]',
        from: '[email protected]',
        subject: 'Testing Nest Mailermodule with template โœ”',
        template: '/index', // The `.pug` or `.hbs` extension is appended automatically.
        context: {  // Data to be sent to template engine.
          code: 'cf1a3f828287',
          username: 'john doe',
        },
      })
      .then((success) => {
        console.log(success)
      })
      .catch((err) => {
        console.log(err)
      });
  }
}

Make a template named folder at the root level of the project and keep all the email-templates in the that folder with .hbs extension. This implementation uses handlebars as a view-engine and outlook as the smtp.

Configuration

Dotenv module has been used for sender's email and password keep. This kit is implemented with outlook smtp, while we can make changes in the app.module.ts configurations for other services. As the nestjs-mailer is built on top of nodemailer, the required configurations can be found here Nodemailer / smtp.

Special thanks to https://github.com/leemunroe/responsive-html-email-template for providing email-templates

nestjs-mailer's People

Contributors

danielebarbaro avatar dependabot[bot] avatar wenderpmachado avatar yanarp avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar

nestjs-mailer's Issues

hi thanks for your repo

Error: read ECONNRESET
at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) {
errno: -4077,
code: 'ESOCKET',
syscall: 'read',
command: 'CONN'

how to solve this
thanks

Doc Request: How To Unit Test?

First of all, thanks for the awesome package โค๏ธ

I started to use this, and everything works fine, but I want to add some unit tests using Jest.

How can I mock and inject the MailerService dependence?

My template is not loaded

My config in app.module.ts:
MailerModule.forRoot({ transport: { host: 'smtp.gmail.com', port: 587, ignoreTLS: false, secure: false, auth: { user: process.env.GMAIL_USER, pass: process.env.GMAIL_PASS, }, }, defaults: { from: '"No Reply" <info@xxxxxxx>', }, // preview: true, template: { dir: process.cwd() + '/src/templates/', adapter: new HandlebarsAdapter(), options: { strict: true, }, }, }),

My config in sendMail:
const sendMail = await this._mailerService.sendMail({ to: user.email, subject: "Confirm Your Email Address", context: { name: 'my name' }, template: 'my-template', });

My mail account receives mail but there is no template.
"@nestjs-modules/mailer": "^1.6.0"
"nodemailer": "^6.7.0"

Use template for both text and html

Hi,
thanks you for this module, it is very helpful.

Context:
I have an issue with my spam score which I can fix by sending both HTML and text version of the email.

** The issue:**
I have to "hardcode" the text version because the template field acts only for the HTML version.

this.mailerService.sendMail({
      from: `"Nekroz - Goblins Market" <${process.env.MAIL_USER ?? ""}>`,
      to: user.email, // list of receivers
      subject: "Goblins Market : bienvenue !", // Subject line
      template: "welcome", // The `.pug`, `.ejs` or `.hbs` extension is appended automatically.
      text: ejs.render(`Hello <%= locals.username %>. ...`,  { username: user.username }), // Template content duplication here
      context: {
        username: user.username,
      },
    });

Do you know a workaround for this ? I can help you with a PR if you provide me some guidelines to respect your module architecture.

Cannot destructure property 'templateName' of 'precompile(...)'

Hi all, ๐Ÿฆ„

Config:

    "@nestjs-modules/mailer": "^1.6.0",
    "nodemailer": "^6.5.0",
    "handlebars": "^4.7.7",

I'm trying to use with handlebars.

App Module:

@Module({
  imports: [
    UserModule,
    AdminModule,
    HotelModule,
    TypeOrmModule.forRoot(),
    ConfigModule.forRoot({ isGlobal: true }),
    MailerModule.forRootAsync({
      useFactory: () => ({
        transport:
          'smtps://no-reply@XXX:[email protected]',
        defaults: {
          from: '"XXX" <[email protected]>',
        },
        template: {
          dir: path.resolve(__dirname, 'templates'),
          adapter: new HandlebarsAdapter(),
          options: {
            strict: true,
          },
        },
      }),
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})

Service:

import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';

@Injectable()
export class UserMailService {
  constructor(private readonly mailerService: MailerService) {}

  sendEmailConfirmation(): void {
    this.mailerService
      .sendMail({
        to: '[email protected]',
        from: '[email protected]',
        subject: 'Testing Nest Mailermodule with template โœ”',
        template: '/welcome',
      })
      .then((success) => {
        console.log(success);
      })
      .catch((err) => {
        console.log(err);
      });
  }
}

I get this error when I use templates.

TypeError: Cannot destructure property 'templateName' of 'precompile(...)' as it is undefined.
    at HandlebarsAdapter.compile (/mnt/c/Users/user/Desktop/web/api/node_modules/@nestjs-modules/mailer/dist/adapters/handlebars.adapter.js:52:17)
    at /mnt/c/Users/user/Desktop/web/api/node_modules/@nestjs-modules/mailer/dist/mailer.service.js:48:40
    at processPlugins (/mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:279:13)
    at /mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:283:17
    at Mail._convertDataImages (/mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:387:20)
    at Mail._defaultPlugins.compile (/mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:31:41)
    at processPlugins (/mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:279:13)
    at Mail._processPlugins (/mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:287:9)
    at Mail.sendMail (/mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:164:14)
    at MailerService.<anonymous> (/mnt/c/Users/user/Desktop/web/api/node_modules/@nestjs-modules/mailer/dist/mailer.service.js:74:51)
(node:8093) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open '/welcome.hbs'
    at Object.openSync (fs.js:476:3)
    at Object.readFileSync (fs.js:377:35)
    at precompile (/mnt/c/Users/user/Desktop/web/api/node_modules/@nestjs-modules/mailer/dist/adapters/handlebars.adapter.js:34:41)
    at HandlebarsAdapter.compile (/mnt/c/Users/user/Desktop/web/api/node_modules/@nestjs-modules/mailer/dist/adapters/handlebars.adapter.js:52:34)
    at /mnt/c/Users/user/Desktop/web/api/node_modules/@nestjs-modules/mailer/dist/mailer.service.js:48:40
    at processPlugins (/mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:279:13)
    at /mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:283:17
    at Mail._convertDataImages (/mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:387:20)
    at Mail._defaultPlugins.compile (/mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:31:41)
    at processPlugins (/mnt/c/Users/user/Desktop/web/api/node_modules/nodemailer/lib/mailer/index.js:279:13)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:8093) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:8093) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I manually copied templates folder to dist to check whether the problem is with paths.
But it asks for templateName which I didn't provide.

Thanks!

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.