1.0.6 • Published 2 years ago

nestjs-email-fork v1.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

A NestJS library to generate adaptive emails via JSX powered by mjml and send them via AWS SES

FORK INFO

Added ability to customize sender per each send

emailService.send(emailFrom, emailTo, emailTemplate, { ...emailTemplateProps});

You can also configure the module and specify EmailFrom there, then this field will be used by default, but the variable in the send method will still overwrite this email if it is filled in.

EmailModule.forRoot({
  from: emailFrom, // "Dev <dev@foo.com>" format also works
  send: true, // Actually send email. It's assumed this is not always wanted aka dev.
  global: true, // Optionally allow EmailService to be used globally without importing module
})

emailFrom example

emailFrom = '"Admin of my site" admin@gmail.com'

How it works

The rendering is powered by mjml with a React wrapper.
This allows email templates & components to be created in a typesafe way while having the complexities of email HTML handled by mjml.

The generated HTML runs through html-to-text to automatically create a text version of the email.
Where needed, this ouput can be customized with our <InText> and <HideInText> components.

After that a MIME message is composed via emailjs.
This merges the HTML, text, attachments, & headers (from, to, etc.) to a string.

With the MIME message finalized it is sent to SES via their v3 SDK.
Their SDK allows for automatic configuration; compared to SMTP which needs to be configured with an explicit server, username, and password.

All of this is wrapped in an NestJS module for easy integration.

There's also an open option to open rendered HTML in browser, which can be useful for development.

Setup

Simple static

EmailModule.forRoot({
  from: 'dev@foo.com', // "Dev <dev@foo.com>" format also works
  send: true, // Actually send email. It's assumed this is not always wanted aka dev.
  global: true, // Optionally allow EmailService to be used globally without importing module
})

See EmailModuleOptions for all options.

Async Configuration

More complex setups can use async configuration (standard to NestJS packages)

Factory function example

EmailModule.forRootAsync({
  useFactory: async (foo: FooService) => ({
    from: await foo.getFromAddress(),
  }),
  import: [FooService],
})

Options class example

EmailModule.forRootAsync({
  useClass: EmailConfig,
  // or
  useExisting: EmailConfig,
})
@Injectable()
export class EmailConfig implements EmailOptionsFactory {
  async createEmailOptions() {
    return {
      from: '',
    };
  }
}

Usage

Define a template

import * as Mjml from 'nestjs-email-fork/templates';
import { Mjml as MjmlRoot } from 'mjml-react';
import * as React from 'react';

export function ForgotPassword({ name, url }: { name: string, url: string }) {
  return (
    <MjmlRoot lang="en">
      <Mjml.Head>
        {/* Title also sets the subject */}
        <Mjml.Title>Forgot Password</Mjml.Title>
      </Mjml.Head>
      <Mjml.Body>

        <Mjml.Section>
          <Mjml.Column padding={0}>
            <Mjml.Text fontSize={24}>
              Hey {name}, passwords are hard
            </Mjml.Text>
          </Mjml.Column>
        </Mjml.Section>

        <Mjml.Section>
          <Mjml.Column>
            <Mjml.Text>
              If you requested this, confirm the password change
            </Mjml.Text>
            <Mjml.Button href={url}>CONFIRM</Mjml.Button>
          </Mjml.Column>
        </Mjml.Section>

      </Mjml.Body>
    </MjmlRoot>
  );
}

This is a single component to show the complete picture. In actual usage it makes more sense to break this up into smaller components, just like would be done with React UIs.

For example, an <Email> wrapping component could be created to wrap Mjml root, Head, Body, setup theme, etc.

A <Heading> component could turn the first section into a one liner.

Call it

import { Injectable } from '@nestjs/common';
import { EmailService } from 'nestjs-email-fork';
import { ForgotPassword } from './forgot-password.template';

@Injectable()
export class UserService {
  constructor(private email: EmailService) {}

  async forgotPassword(emailAddress: string) {
    const user = await lookupByEmail(emailAddress);
    const emailFrom = '"Admin of my site" admin@gmail.com'
    await this.email.send(emailFrom, user.email, ForgotPassword, {
      // type safe parameters per template
      name: user.name,
      url: 'https://foo.com/signed-url/...',
    });
  }
}