plugin.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. ProcessContext,
  11. registerPluginStartupMessage,
  12. Type,
  13. VendurePlugin,
  14. } from '@vendure/core';
  15. import { isDevModeOptions } from './common';
  16. import { EMAIL_PLUGIN_OPTIONS, loggerCtx } from './constants';
  17. import { DevMailbox } from './dev-mailbox';
  18. import { EmailProcessor } from './email-processor';
  19. import { EmailEventHandler, EmailEventHandlerWithAsyncData } from './event-handler';
  20. import {
  21. EmailPluginDevModeOptions,
  22. EmailPluginOptions,
  23. EventWithContext,
  24. IntermediateEmailDetails,
  25. } from './types';
  26. /**
  27. * @description
  28. * The EmailPlugin creates and sends transactional emails based on Vendure events. By default it uses an [MJML](https://mjml.io/)-based
  29. * email generator to generate the email body and [Nodemailer](https://nodemailer.com/about/) to send the emails.
  30. *
  31. * ## Installation
  32. *
  33. * `yarn add \@vendure/email-plugin`
  34. *
  35. * or
  36. *
  37. * `npm install \@vendure/email-plugin`
  38. *
  39. * @example
  40. * ```ts
  41. * import { defaultEmailHandlers, EmailPlugin } from '\@vendure/email-plugin';
  42. *
  43. * const config: VendureConfig = {
  44. * // Add an instance of the plugin to the plugins array
  45. * plugins: [
  46. * EmailPlugin.init({
  47. * handlers: defaultEmailHandlers,
  48. * templatePath: path.join(__dirname, 'vendure/email/templates'),
  49. * transport: {
  50. * type: 'smtp',
  51. * host: 'smtp.example.com',
  52. * port: 587,
  53. * auth: {
  54. * user: 'username',
  55. * pass: 'password',
  56. * }
  57. * },
  58. * }),
  59. * ],
  60. * };
  61. * ```
  62. *
  63. * ## Email templates
  64. *
  65. * In the example above, the plugin has been configured to look in `<app-root>/vendure/email/templates`
  66. * for the email template files. If you used `\@vendure/create` to create your application, the templates will have
  67. * been copied to that location during setup.
  68. *
  69. * If you are installing the EmailPlugin separately, then you'll need to copy the templates manually from
  70. * `node_modules/\@vendure/email-plugin/templates` to a location of your choice, and then point the `templatePath` config
  71. * property at that directory.
  72. *
  73. * ## Customizing templates
  74. *
  75. * Emails are generated from templates which use [MJML](https://mjml.io/) syntax. MJML is an open-source HTML-like markup
  76. * language which makes the task of creating responsive email markup simple. By default, the templates are installed to
  77. * `<project root>/vendure/email/templates` and can be freely edited.
  78. *
  79. * Dynamic data such as the recipient's name or order items are specified using [Handlebars syntax](https://handlebarsjs.com/):
  80. *
  81. * ```HTML
  82. * <p>Dear {{ order.customer.firstName }} {{ order.customer.lastName }},</p>
  83. *
  84. * <p>Thank you for your order!</p>
  85. *
  86. * <mj-table cellpadding="6px">
  87. * {{#each order.lines }}
  88. * <tr class="order-row">
  89. * <td>{{ quantity }} x {{ productVariant.name }}</td>
  90. * <td>{{ productVariant.quantity }}</td>
  91. * <td>{{ formatMoney totalPrice }}</td>
  92. * </tr>
  93. * {{/each}}
  94. * </mj-table>
  95. * ```
  96. *
  97. * ### Handlebars helpers
  98. *
  99. * The following helper functions are available for use in email templates:
  100. *
  101. * * `formatMoney`: Formats an amount of money (which are always stored as integers in Vendure) as a decimal, e.g. `123` => `1.23`
  102. * * `formatDate`: Formats a Date value with the [dateformat](https://www.npmjs.com/package/dateformat) package.
  103. *
  104. * ## Extending the default email handlers
  105. *
  106. * The `defaultEmailHandlers` array defines the default handlers such as for handling new account registration, order confirmation, password reset
  107. * etc. These defaults can be extended by adding custom templates for languages other than the default, or even completely new types of emails
  108. * which respond to any of the available [VendureEvents](/docs/typescript-api/events/). See the {@link EmailEventHandler} documentation for
  109. * details on how to do so.
  110. *
  111. * ## Dev mode
  112. *
  113. * For development, the `transport` option can be replaced by `devMode: true`. Doing so configures Vendure to use the
  114. * file transport (See {@link FileTransportOptions}) and outputs emails as rendered HTML files in the directory specified by the
  115. * `outputPath` property.
  116. *
  117. * ```ts
  118. * EmailPlugin.init({
  119. * devMode: true,
  120. * route: 'mailbox',
  121. * handlers: defaultEmailHandlers,
  122. * templatePath: path.join(__dirname, 'vendure/email/templates'),
  123. * outputPath: path.join(__dirname, 'test-emails'),
  124. * })
  125. * ```
  126. *
  127. * ### Dev mailbox
  128. *
  129. * In dev mode, a webmail-like interface available at the `/mailbox` path, e.g.
  130. * http://localhost:3000/mailbox. This is a simple way to view the output of all emails generated by the EmailPlugin while in dev mode.
  131. *
  132. * ## Troubleshooting SMTP Connections
  133. *
  134. * If you are having trouble sending email over and SMTP connection, set the `logging` and `debug` options to `true`. This will
  135. * send detailed information from the SMTP transporter to the configured logger (defaults to console). For maximum detail combine
  136. * this with a detail log level in the configured VendureLogger:
  137. *
  138. * ```TypeScript
  139. * const config: VendureConfig = {
  140. * logger: new DefaultLogger({ level: LogLevel.Debug })
  141. * // ...
  142. * plugins: [
  143. * EmailPlugin.init({
  144. * // ...
  145. * transport: {
  146. * type: 'smtp',
  147. * host: 'smtp.example.com',
  148. * port: 587,
  149. * auth: {
  150. * user: 'username',
  151. * pass: 'password',
  152. * },
  153. * logging: true,
  154. * debug: true,
  155. * },
  156. * }),
  157. * ],
  158. * };
  159. * ```
  160. *
  161. * @docsCategory EmailPlugin
  162. */
  163. @VendurePlugin({
  164. imports: [PluginCommonModule],
  165. providers: [{ provide: EMAIL_PLUGIN_OPTIONS, useFactory: () => EmailPlugin.options }, EmailProcessor],
  166. })
  167. export class EmailPlugin implements OnApplicationBootstrap, NestModule {
  168. private static options: EmailPluginOptions | EmailPluginDevModeOptions;
  169. private devMailbox: DevMailbox | undefined;
  170. private jobQueue: JobQueue<IntermediateEmailDetails> | undefined;
  171. private testingProcessor: EmailProcessor | undefined;
  172. /** @internal */
  173. constructor(
  174. private eventBus: EventBus,
  175. private moduleRef: ModuleRef,
  176. private emailProcessor: EmailProcessor,
  177. private jobQueueService: JobQueueService,
  178. private processContext: ProcessContext,
  179. ) {}
  180. /**
  181. * Set the plugin options.
  182. */
  183. static init(options: EmailPluginOptions | EmailPluginDevModeOptions): Type<EmailPlugin> {
  184. this.options = options;
  185. return EmailPlugin;
  186. }
  187. /** @internal */
  188. async onApplicationBootstrap(): Promise<void> {
  189. const options = EmailPlugin.options;
  190. await this.setupEventSubscribers();
  191. if (!isDevModeOptions(options) && options.transport.type === 'testing') {
  192. // When running tests, we don't want to go through the JobQueue system,
  193. // so we just call the email sending logic directly.
  194. this.testingProcessor = new EmailProcessor(options);
  195. await this.testingProcessor.init();
  196. } else {
  197. await this.emailProcessor.init();
  198. this.jobQueue = await this.jobQueueService.createQueue({
  199. name: 'send-email',
  200. process: job => {
  201. return this.emailProcessor.process(job.data);
  202. },
  203. });
  204. }
  205. }
  206. configure(consumer: MiddlewareConsumer) {
  207. const options = EmailPlugin.options;
  208. if (isDevModeOptions(options) && this.processContext.isServer) {
  209. Logger.info('Creating dev mailbox middleware', loggerCtx);
  210. this.devMailbox = new DevMailbox();
  211. consumer.apply(this.devMailbox.serve(options)).forRoutes(options.route);
  212. this.devMailbox.handleMockEvent((handler, event) => this.handleEvent(handler, event));
  213. registerPluginStartupMessage('Dev mailbox', options.route);
  214. }
  215. }
  216. private async setupEventSubscribers() {
  217. for (const handler of EmailPlugin.options.handlers) {
  218. this.eventBus.ofType(handler.event).subscribe(event => {
  219. return this.handleEvent(handler, event);
  220. });
  221. }
  222. }
  223. private async handleEvent(
  224. handler: EmailEventHandler | EmailEventHandlerWithAsyncData<any>,
  225. event: EventWithContext,
  226. ) {
  227. Logger.debug(`Handling event "${handler.type}"`, loggerCtx);
  228. const { type } = handler;
  229. try {
  230. const injector = new Injector(this.moduleRef);
  231. const result = await handler.handle(
  232. event as any,
  233. EmailPlugin.options.globalTemplateVars,
  234. injector,
  235. );
  236. if (!result) {
  237. return;
  238. }
  239. if (this.jobQueue) {
  240. await this.jobQueue.add(result, { retries: 5 });
  241. } else if (this.testingProcessor) {
  242. await this.testingProcessor.process(result);
  243. }
  244. } catch (e) {
  245. Logger.error(e.message, loggerCtx, e.stack);
  246. }
  247. }
  248. }