From 80660982427349b473acdbf96b9c01c5cae8628a Mon Sep 17 00:00:00 2001 From: Richard Bergsma Date: Sat, 7 Jun 2025 02:04:38 +0200 Subject: [PATCH] Update email handler to improve from address handling and enhance error logging - Modify the from address logic to use a default 'noreply' address if SMTP_USER is not set in production. - Add debug logging for email sending details, including connection target and sender/recipient information. - Simplify error logging by removing specific SMTP error messages while retaining the full error stack for troubleshooting. --- src/utils/email-handler.ts | 29 ++++++----------------------- 1 file changed, 6 insertions(+), 23 deletions(-) diff --git a/src/utils/email-handler.ts b/src/utils/email-handler.ts index a600d16..69e1246 100644 --- a/src/utils/email-handler.ts +++ b/src/utils/email-handler.ts @@ -170,8 +170,7 @@ export async function sendEmail(to: string, subject: string, html: string, text: } try { - // Ensure from address matches SMTP_USER for ProtonMail - const fromAddress = isProduction ? `"${WEBSITE_NAME}" <${SMTP_USER}>` : `"${WEBSITE_NAME}" <${ADMIN_EMAIL}>`; + const fromAddress = isProduction ? `"${WEBSITE_NAME}" <${SMTP_USER || 'noreply@' + WEBSITE_NAME}>` : `"${WEBSITE_NAME}" <${ADMIN_EMAIL}>`; const mailOptions = { from: fromAddress, @@ -181,33 +180,17 @@ export async function sendEmail(to: string, subject: string, html: string, text: text, }; + // Log the connection target + console.log(`[MAILER DEBUG] Sending via: ${SMTP_HOST}:${SMTP_PORT}`); + console.log(`[MAILER DEBUG] From: ${fromAddress} → To: ${to}`); + await transporter.sendMail(mailOptions); logEmailAttempt(true, to, subject); return true; } catch (error) { logEmailAttempt(false, to, subject, error as Error); - - // Enhanced error logging for SMTP issues - if (isProduction) { - console.error('Error sending email:', error); - - // Log more detailed information for SMTP errors - if (error instanceof Error) { - console.error('Error name:', error.name); - console.error('Error message:', error.message); - - // Log additional details for specific error types - if (error.name === 'Error' && error.message.includes('ECONNREFUSED')) { - console.error('SMTP Connection Refused: Check if the SMTP server is reachable and the port is correct'); - } else if (error.message.includes('Invalid login')) { - console.error('SMTP Authentication Failed: Check your username and password'); - } else if (error.message.includes('certificate')) { - console.error('SSL/TLS Certificate Error: There might be an issue with the server certificate'); - } - } - } - + console.error('Full SMTP error stack:', error); return false; } }