plugin.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import { MiddlewareConsumer, NestModule, OnApplicationBootstrap } from '@nestjs/common';
  2. import { ModuleRef } from '@nestjs/core';
  3. import {
  4. EventBus,
  5. Injector,
  6. JobQueue,
  7. JobQueueService,
  8. Logger,
  9. PluginCommonModule,
  10. registerPluginStartupMessage,
  11. Type,
  12. VendurePlugin,
  13. } from '@vendure/core';
  14. import { isDevModeOptions } from './common';
  15. import { EMAIL_PLUGIN_OPTIONS, loggerCtx } from './constants';
  16. import { DevMailbox } from './dev-mailbox';
  17. import { EmailProcessor } from './email-processor';
  18. import { EmailEventHandler, EmailEventHandlerWithAsyncData } from './event-handler';
  19. import {
  20. EmailPluginDevModeOptions,
  21. EmailPluginOptions,
  22. EventWithContext,
  23. IntermediateEmailDetails,
  24. } from './types';
  25. /**
  26. * @description
  27. * The EmailPlugin creates and sends transactional emails based on Vendure events. By default 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 emails.
  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. * EmailPlugin.init({
  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. * route: 'mailbox',
  120. * handlers: defaultEmailHandlers,
  121. * templatePath: path.join(__dirname, 'vendure/email/templates'),
  122. * outputPath: path.join(__dirname, 'test-emails'),
  123. * })
  124. * ```
  125. *
  126. * ### Dev mailbox
  127. *
  128. * In dev mode, 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. * ## Troubleshooting SMTP Connections
  132. *
  133. * If you are having trouble sending email over and SMTP connection, set the `logging` and `debug` options to `true`. This will
  134. * send detailed information from the SMTP transporter to the configured logger (defaults to console). For maximum detail combine
  135. * this with a detail log level in the configured VendureLogger:
  136. *
  137. * ```TypeScript
  138. * const config: VendureConfig = {
  139. * logger: new DefaultLogger({ level: LogLevel.Debug })
  140. * // ...
  141. * plugins: [
  142. * EmailPlugin.init({
  143. * // ...
  144. * transport: {
  145. * type: 'smtp',
  146. * host: 'smtp.example.com',
  147. * port: 587,
  148. * auth: {
  149. * user: 'username',
  150. * pass: 'password',
  151. * },
  152. * logging: true,
  153. * debug: true,
  154. * },
  155. * }),
  156. * ],
  157. * };
  158. * ```
  159. *
  160. * @docsCategory EmailPlugin
  161. */
  162. @VendurePlugin({
  163. imports: [PluginCommonModule],
  164. providers: [{ provide: EMAIL_PLUGIN_OPTIONS, useFactory: () => EmailPlugin.options }, EmailProcessor],
  165. })
  166. export class EmailPlugin implements OnApplicationBootstrap, NestModule {
  167. private static options: EmailPluginOptions | EmailPluginDevModeOptions;
  168. private devMailbox: DevMailbox | undefined;
  169. private jobQueue: JobQueue<IntermediateEmailDetails> | undefined;
  170. private testingProcessor: EmailProcessor | undefined;
  171. /** @internal */
  172. constructor(
  173. private eventBus: EventBus,
  174. private moduleRef: ModuleRef,
  175. private emailProcessor: EmailProcessor,
  176. private jobQueueService: JobQueueService,
  177. ) {}
  178. /**
  179. * Set the plugin options.
  180. */
  181. static init(options: EmailPluginOptions | EmailPluginDevModeOptions): Type<EmailPlugin> {
  182. this.options = options;
  183. return EmailPlugin;
  184. }
  185. /** @internal */
  186. async onApplicationBootstrap(): Promise<void> {
  187. const options = EmailPlugin.options;
  188. await this.setupEventSubscribers();
  189. if (!isDevModeOptions(options) && options.transport.type === 'testing') {
  190. // When running tests, we don't want to go through the JobQueue system,
  191. // so we just call the email sending logic directly.
  192. this.testingProcessor = new EmailProcessor(options);
  193. await this.testingProcessor.init();
  194. } else {
  195. await this.emailProcessor.init();
  196. this.jobQueue = await this.jobQueueService.createQueue({
  197. name: 'send-email',
  198. process: job => {
  199. return this.emailProcessor.process(job.data);
  200. },
  201. });
  202. }
  203. }
  204. configure(consumer: MiddlewareConsumer) {
  205. const options = EmailPlugin.options;
  206. if (isDevModeOptions(options)) {
  207. Logger.info('Creating dev mailbox middleware', loggerCtx);
  208. this.devMailbox = new DevMailbox();
  209. consumer.apply(this.devMailbox.serve(options)).forRoutes(options.route);
  210. this.devMailbox.handleMockEvent((handler, event) => this.handleEvent(handler, event));
  211. registerPluginStartupMessage('Dev mailbox', options.route);
  212. }
  213. }
  214. private async setupEventSubscribers() {
  215. for (const handler of EmailPlugin.options.handlers) {
  216. this.eventBus.ofType(handler.event).subscribe(event => {
  217. return this.handleEvent(handler, event);
  218. });
  219. }
  220. }
  221. private async handleEvent(
  222. handler: EmailEventHandler | EmailEventHandlerWithAsyncData<any>,
  223. event: EventWithContext,
  224. ) {
  225. Logger.debug(`Handling event "${handler.type}"`, loggerCtx);
  226. const { type } = handler;
  227. try {
  228. const injector = new Injector(this.moduleRef);
  229. const result = await handler.handle(
  230. event as any,
  231. EmailPlugin.options.globalTemplateVars,
  232. injector,
  233. );
  234. if (!result) {
  235. return;
  236. }
  237. if (this.jobQueue) {
  238. await this.jobQueue.add(result);
  239. } else if (this.testingProcessor) {
  240. await this.testingProcessor.process(result);
  241. }
  242. } catch (e) {
  243. Logger.error(e.message, loggerCtx, e.stack);
  244. }
  245. }
  246. }