Refactor email handling to enhance SMTP configuration and error logging

- Updated the email transporter initialization to support secure connections and dynamic port settings.
- Added authentication handling for SMTP credentials if provided.
- Improved error logging during SMTP verification to include detailed connection information.
- Adjusted the sendEmail function signature for consistency with updated parameters.
This commit is contained in:
2025-11-02 00:47:49 +01:00
parent 84a5e71b95
commit 9544b6800d

View File

@@ -24,21 +24,47 @@ let transporter: nodemailer.Transporter;
// Initialize the transporter based on environment
function initializeTransporter() {
if (isProduction && SMTP_HOST) {
// Use local Postfix mail relay (no authentication)
transporter = nodemailer.createTransport({
host: SMTP_HOST,
port: parseInt(SMTP_PORT, 10) || 25, // default to port 25 if not set
secure: false, // No SSL for local relay
tls: {
rejectUnauthorized: false, // Accept self-signed certificates if present
},
});
const port = parseInt(SMTP_PORT, 10) || 587;
// Determine if secure connection (port 465 typically uses SSL)
const secure = port === 465;
transporter.verify((error, success) => {
// Build transporter config
const transporterConfig: {
host: string;
port: number;
secure: boolean;
tls: { rejectUnauthorized: boolean };
auth?: { user: string; pass: string };
} = {
host: SMTP_HOST,
port: port,
secure: secure,
tls: {
rejectUnauthorized: false, // Accept self-signed certificates (useful for Mailcow)
},
};
// Add authentication if credentials are provided
if (SMTP_USER && SMTP_PASS) {
transporterConfig.auth = {
user: SMTP_USER,
pass: SMTP_PASS,
};
}
transporter = nodemailer.createTransport(transporterConfig);
transporter.verify((error, _success) => {
if (error) {
console.error('❌ SMTP connection error:', error);
console.error('❌ SMTP connection error:', error.message);
console.error(' Host:', SMTP_HOST);
console.error(' Port:', port);
console.error(' Auth:', SMTP_USER ? 'Yes' : 'No');
} else {
console.log('✅ SMTP server is ready to take messages.');
console.log(' Host:', SMTP_HOST);
console.log(' Port:', port);
console.log(' Auth:', SMTP_USER ? 'Yes' : 'No');
}
});
} else {
@@ -140,7 +166,7 @@ export function logEmailAttempt(success: boolean, recipient: string, subject: st
}
// Send an email
export async function sendEmail(to: string, subject: string, html: string, text: string, domain?: string): Promise<boolean> {
export async function sendEmail(to: string, subject: string, html: string, text: string, _domain?: string): Promise<boolean> {
// Initialize transporter if not already done
if (!transporter) {
initializeTransporter();