| 1 | import { existsSync } from 'node:fs'; |
| 2 | import { delimiter, join |
| 3 | import { Global, Module |
| 4 | import { ConfigModule, ConfigService |
| 5 | import { MailerModule } |
| 6 | import { ReactAdapter } |
| 7 | |
| 8 | import { MailService } |
| 9 | import { proxyTransport } |
| 10 | |
| 11 | /** The local sendmail binary: SENDMAIL_PATH, else the first `sendmail` on PATH or in the usual sbin directories. Windows has none built in; a drop-in such as sendmail.exe on PATH is found the same way. */ |
| 12 | export function sendmailPath( |
| 13 | config: ConfigService |
| 14 | env: NodeJS |
| 15 | ): string | undefined |
| 16 | const configured = |
| 17 | if (configured) return |
| 18 | const dirs = |
| 19 | ...(env.PATH |
| 20 | '/usr/sbin', |
| 21 | '/usr/lib', |
| 22 | ].filter(Boolean) |
| 23 | const names = |
| 24 | process.platform === |
| 25 | return dirs |
| 26 | .flatMap((dir) |
| 27 | .find((file) |
| 28 | } |
| 29 | |
| 30 | /** True once any delivery route (HTTP relay, SMTP, or a local sendmail) is available. */ |
| 31 | export function mailConfigured(config |
| 32 | return Boolean( |
| 33 | config.get<string |
| 34 | config.get<string |
| 35 | sendmailPath(config), |
| 36 | ); |
| 37 | } |
| 38 | |
| 39 | /** Self-hosters without mail configured keep email verification off. */ |
| 40 | export function emailVerificationEnabled(config |
| 41 | return config.get |
| 42 | } |
| 43 | |
| 44 | @Global() |
| 45 | @Module({ |
| 46 | imports: [ |
| 47 | MailerModule.forRootAsync({ |
| 48 | imports: [ConfigModule], |
| 49 | inject: [ConfigService], |
| 50 | useFactory: (config: |
| 51 | const proxyUrl = |
| 52 | const host = |
| 53 | const sendmail = |
| 54 | |
| 55 | if ( |
| 56 | !proxyUrl && |
| 57 | !host && |
| 58 | !sendmail && |
| 59 | emailVerificationEnabled(config) |
| 60 | ) { |
| 61 | throw new Error( |
| 62 | 'EMAIL_VERIFICATION_ENABLED requires EMAIL_PROXY, MAIL_HOST/MAIL_PORT/MAIL_USER/MAIL_PASSWORD, or a sendmail binary', |
| 63 | ); |
| 64 | } |
| 65 | |
| 66 | return { |
| 67 | transport: proxyUrl |
| 68 | ? proxyTransport(proxyUrl, |
| 69 | : host |
| 70 | ? { |
| 71 | host, |
| 72 | port: Number(config |
| 73 | secure: config.get |
| 74 | auth: { |
| 75 | user: config.getOrThrow |
| 76 | pass: config.getOrThrow |
| 77 | }, |
| 78 | } |
| 79 | : sendmail |
| 80 | ? { sendmail: true, |
| 81 | : // No mail configured and nothing sends mail: swallow instead of crashing. |
| 82 | { jsonTransport: true }, |
| 83 | defaults: { |
| 84 | from: |
| 85 | config.get<string |
| 86 | 'Ghost <noreply@ghost.local>', |
| 87 | }, |
| 88 | // Templates are compiled to dist/mail/templates alongside this module. |
| 89 | template: { |
| 90 | dir: join(import. |
| 91 | adapter: new ReactAdapter |
| 92 | }, |
| 93 | }; |
| 94 | }, |
| 95 | }), |
| 96 | ], |
| 97 | providers: [MailService], |
| 98 | exports: [MailService], |
| 99 | }) |
| 100 | export class MailModule |