|
| 1 | +import SMTPTransport from "nodemailer/lib/smtp-transport" |
1 | 2 | import { SmtpSettings } from "../../prisma/client" |
2 | 3 | import nodemailer from "nodemailer" |
3 | 4 |
|
@@ -32,38 +33,47 @@ interface SendEmailResponse { |
32 | 33 | messageId?: string |
33 | 34 | } |
34 | 35 |
|
| 36 | +type TransportOptions = SMTPTransport | SMTPTransport.Options | string |
| 37 | + |
35 | 38 | export class Mailer { |
36 | 39 | private transporter: nodemailer.Transporter |
37 | 40 |
|
38 | 41 | constructor(smtpSettings: SmtpSettings) { |
39 | | - const startTls = { |
40 | | - port: 587, |
41 | | - secure: false, |
42 | | - requireTLS: true, |
43 | | - } |
44 | | - |
45 | | - const sslTls = { |
46 | | - port: 465, |
47 | | - secure: true, |
48 | | - } |
49 | | - |
50 | | - const tlsOpts = |
51 | | - smtpSettings.encryption === "STARTTLS" |
52 | | - ? startTls |
53 | | - : smtpSettings.encryption === "SSL_TLS" |
54 | | - ? sslTls |
55 | | - : { port: smtpSettings.port } |
56 | | - |
57 | | - this.transporter = nodemailer.createTransport({ |
58 | | - connectionTimeout: smtpSettings.timeout, |
| 42 | + let transportOptions: TransportOptions = { |
59 | 43 | host: smtpSettings.host, |
| 44 | + port: smtpSettings.port, |
| 45 | + connectionTimeout: smtpSettings.timeout, |
60 | 46 | auth: { |
61 | 47 | user: smtpSettings.username, |
62 | 48 | pass: smtpSettings.password, |
63 | 49 | }, |
64 | | - requireTLS: smtpSettings.secure, |
65 | | - ...tlsOpts, |
66 | | - }) |
| 50 | + } |
| 51 | + |
| 52 | + if (smtpSettings.encryption === "STARTTLS") { |
| 53 | + transportOptions = { |
| 54 | + ...transportOptions, |
| 55 | + port: smtpSettings.port || 587, // Default STARTTLS port |
| 56 | + secure: false, // Use STARTTLS |
| 57 | + requireTLS: true, // Require STARTTLS upgrade |
| 58 | + } |
| 59 | + } else if (smtpSettings.encryption === "SSL_TLS") { |
| 60 | + transportOptions = { |
| 61 | + ...transportOptions, |
| 62 | + port: smtpSettings.port || 465, // Default SSL/TLS port |
| 63 | + secure: true, // Use direct TLS connection |
| 64 | + } |
| 65 | + } else { |
| 66 | + // NONE encryption |
| 67 | + transportOptions = { |
| 68 | + ...transportOptions, |
| 69 | + port: smtpSettings.port || 25, // Default non-encrypted port |
| 70 | + secure: false, |
| 71 | + requireTLS: false, // Explicitly disable TLS requirement |
| 72 | + ignoreTLS: true, // Optionally ignore TLS advertised by server if needed |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + this.transporter = nodemailer.createTransport(transportOptions) |
67 | 77 | } |
68 | 78 |
|
69 | 79 | async sendEmail(options: SendMailOptions): Promise<SendEmailResponse> { |
|
0 commit comments