plugin.ts 8.9 KB

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