plugin.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import {
  2. createProxyHandler,
  3. EventBus,
  4. EventBusModule,
  5. InternalServerError,
  6. Logger,
  7. OnVendureBootstrap,
  8. OnVendureClose,
  9. RuntimeVendureConfig,
  10. Type,
  11. VendurePlugin,
  12. } from '@vendure/core';
  13. import fs from 'fs-extra';
  14. import { DevMailbox } from './dev-mailbox';
  15. import { EmailSender } from './email-sender';
  16. import { EmailEventHandler } from './event-listener';
  17. import { HandlebarsMjmlGenerator } from './handlebars-mjml-generator';
  18. import { TemplateLoader } from './template-loader';
  19. import {
  20. EmailPluginDevModeOptions,
  21. EmailPluginOptions,
  22. EmailTransportOptions,
  23. EventWithContext,
  24. } from './types';
  25. /**
  26. * @description
  27. * The EmailPlugin creates and sends transactional emails based on Vendure events. It uses an [MJML](https://mjml.io/)-based
  28. * email generator to generate the email body and [Nodemailer](https://nodemailer.com/about/) to send the emais.
  29. *
  30. * ## Installation
  31. *
  32. * `yarn add \@vendure/email-plugin`
  33. *
  34. * or
  35. *
  36. * `npm install \@vendure/email-plugin`
  37. *
  38. * @example
  39. * ```ts
  40. * import { defaultEmailHandlers, EmailPlugin } from '\@vendure/email-plugin';
  41. *
  42. * const config: VendureConfig = {
  43. * // Add an instance of the plugin to the plugins array
  44. * plugins: [
  45. * new EmailPlugin({
  46. * handlers: defaultEmailHandlers,
  47. * templatePath: path.join(__dirname, 'vendure/email/templates'),
  48. * transport: {
  49. * type: 'smtp',
  50. * host: 'smtp.example.com',
  51. * port: 587,
  52. * auth: {
  53. * user: 'username',
  54. * pass: 'password',
  55. * }
  56. * },
  57. * }),
  58. * ],
  59. * };
  60. * ```
  61. *
  62. * ## Email templates
  63. *
  64. * In the example above, the plugin has been configured to look in `<app-root>/vendure/email/templates`
  65. * for the email template files. If you used `\@vendure/create` to create your application, the templates will have
  66. * been copied to that location during setup.
  67. *
  68. * If you are installing the EmailPlugin separately, then you'll need to copy the templates manually from
  69. * `node_modules/\@vendure/email-plugin/templates` to a location of your choice, and then point the `templatePath` config
  70. * property at that directory.
  71. *
  72. * ## Customizing templates
  73. *
  74. * Emails are generated from templates which use [MJML](https://mjml.io/) syntax. MJML is an open-source HTML-like markup
  75. * language which makes the task of creating responsive email markup simple. By default, the templates are installed to
  76. * `<project root>/vendure/email/templates` and can be freely edited.
  77. *
  78. * Dynamic data such as the recipient's name or order items are specified using [Handlebars syntax](https://handlebarsjs.com/):
  79. *
  80. * ```HTML
  81. * <p>Dear {{ order.customer.firstName }} {{ order.customer.lastName }},</p>
  82. *
  83. * <p>Thank you for your order!</p>
  84. *
  85. * <mj-table cellpadding="6px">
  86. * {{#each order.lines }}
  87. * <tr class="order-row">
  88. * <td>{{ quantity }} x {{ productVariant.name }}</td>
  89. * <td>{{ productVariant.quantity }}</td>
  90. * <td>{{ formatMoney totalPrice }}</td>
  91. * </tr>
  92. * {{/each}}
  93. * </mj-table>
  94. * ```
  95. *
  96. * ### Handlebars helpers
  97. *
  98. * The following helper functions are available for use in email templates:
  99. *
  100. * * `formatMoney`: Formats an amount of money (which are always stored as integers in Vendure) as a decimal, e.g. `123` => `1.23`
  101. * * `formatDate`: Formats a Date value with the [dateformat](https://www.npmjs.com/package/dateformat) package.
  102. *
  103. * ## Extending the default email handlers
  104. *
  105. * The `defaultEmailHandlers` array defines the default handlers such as for handling new account registration, order confirmation, password reset
  106. * etc. These defaults can be extended by adding custom templates for languages other than the default, or even completely new types of emails
  107. * which respond to any of the available [VendureEvents](/docs/typescript-api/events/). See the {@link EmailEventHandler} documentation for
  108. * details on how to do so.
  109. *
  110. * ## Dev mode
  111. *
  112. * For development, the `transport` option can be replaced by `devMode: true`. Doing so configures Vendure to use the
  113. * file transport (See {@link FileTransportOptions}) and outputs emails as rendered HTML files in the directory specified by the
  114. * `outputPath` property.
  115. *
  116. * ```ts
  117. * EmailPlugin.init({
  118. * devMode: true,
  119. * handlers: defaultEmailHandlers,
  120. * templatePath: path.join(__dirname, 'vendure/email/templates'),
  121. * outputPath: path.join(__dirname, 'test-emails'),
  122. * mailboxPort: 5003,
  123. * })
  124. * ```
  125. *
  126. * ### Dev mailbox
  127. *
  128. * In dev mode, specifying the optional `mailboxPort` will start a webmail-like interface available at the `/mailbox` path, e.g.
  129. * http://localhost:3000/mailbox. This is a simple way to view the output of all emails generated by the EmailPlugin while in dev mode.
  130. *
  131. * @docsCategory EmailPlugin
  132. */
  133. @VendurePlugin({
  134. imports: [EventBusModule],
  135. configuration: config => EmailPlugin.configure(config),
  136. })
  137. export class EmailPlugin implements OnVendureBootstrap, OnVendureClose {
  138. private static options: EmailPluginOptions | EmailPluginDevModeOptions;
  139. private transport: EmailTransportOptions;
  140. private templateLoader: TemplateLoader;
  141. private emailSender: EmailSender;
  142. private generator: HandlebarsMjmlGenerator;
  143. private devMailbox: DevMailbox | undefined;
  144. /** @internal */
  145. constructor(private eventBus: EventBus) {}
  146. /**
  147. * Set the plugin options.
  148. */
  149. static init(options: EmailPluginOptions | EmailPluginDevModeOptions): Type<EmailPlugin> {
  150. this.options = options;
  151. return EmailPlugin;
  152. }
  153. /** @internal */
  154. static configure(config: RuntimeVendureConfig): RuntimeVendureConfig {
  155. if (isDevModeOptions(this.options) && this.options.mailboxPort !== undefined) {
  156. const route = 'mailbox';
  157. config.middleware.push({
  158. handler: createProxyHandler({ port: this.options.mailboxPort, route, label: 'Dev Mailbox' }),
  159. route,
  160. });
  161. }
  162. return config;
  163. }
  164. /** @internal */
  165. async onVendureBootstrap(): Promise<void> {
  166. const options = EmailPlugin.options;
  167. if (isDevModeOptions(options)) {
  168. this.transport = {
  169. type: 'file',
  170. raw: false,
  171. outputPath: options.outputPath,
  172. };
  173. } else {
  174. if (!options.transport) {
  175. throw new InternalServerError(
  176. `When devMode is not set to true, the 'transport' property must be set.`,
  177. );
  178. }
  179. this.transport = options.transport;
  180. }
  181. this.templateLoader = new TemplateLoader(options.templatePath);
  182. this.emailSender = new EmailSender();
  183. this.generator = new HandlebarsMjmlGenerator();
  184. if (isDevModeOptions(options) && options.mailboxPort !== undefined) {
  185. this.devMailbox = new DevMailbox();
  186. this.devMailbox.serve(options);
  187. this.devMailbox.handleMockEvent((handler, event) => this.handleEvent(handler, event));
  188. }
  189. await this.setupEventSubscribers();
  190. if (this.generator.onInit) {
  191. await this.generator.onInit.call(this.generator, options);
  192. }
  193. }
  194. /** @internal */
  195. async onVendureClose() {
  196. if (this.devMailbox) {
  197. this.devMailbox.destroy();
  198. }
  199. }
  200. private async setupEventSubscribers() {
  201. for (const handler of EmailPlugin.options.handlers) {
  202. this.eventBus.subscribe(handler.event, event => {
  203. return this.handleEvent(handler, event);
  204. });
  205. }
  206. if (this.transport.type === 'file') {
  207. // ensure the configured directory exists before
  208. // we attempt to write files to it
  209. const emailPath = this.transport.outputPath;
  210. await fs.ensureDir(emailPath);
  211. }
  212. }
  213. private async handleEvent(handler: EmailEventHandler, event: EventWithContext) {
  214. Logger.debug(`Handling event "${handler.type}"`, 'EmailPlugin');
  215. const { type } = handler;
  216. const result = handler.handle(event, EmailPlugin.options.globalTemplateVars);
  217. if (!result) {
  218. return;
  219. }
  220. const bodySource = await this.templateLoader.loadTemplate(type, result.templateFile);
  221. const generated = await this.generator.generate(result.subject, bodySource, result.templateVars);
  222. const emailDetails = { ...generated, recipient: result.recipient };
  223. await this.emailSender.send(emailDetails, this.transport);
  224. }
  225. }
  226. function isDevModeOptions(
  227. input: EmailPluginOptions | EmailPluginDevModeOptions,
  228. ): input is EmailPluginDevModeOptions {
  229. return (input as EmailPluginDevModeOptions).devMode === true;
  230. }