import { getAuthHeaders, getBaseUrl, validateEmail } from '../utils'; import { SettingsApiResponse } from '../types'; const createEmailTemplate = (template: string, data: any): { subject: string; htmlBody: string } => { let subject = 'Test Email from CheckCle'; let htmlBody = `

Test Email

This is a test email from your monitoring system.

If you received this email, your SMTP configuration is working correctly.


Sent from CheckCle Monitoring System
Template: ${template}
${data.collection ? `Collection: ${data.collection}` : ''}

`; switch (template) { case 'verification': subject = 'Email Verification Test - CheckCle'; htmlBody = `

Email Verification Test

This is a test of the email verification template.

If you received this email, your SMTP configuration is working correctly.

Template: Verification Email

Collection: ${data.collection || '_superusers'}


Sent from CheckCle Monitoring System

`; break; case 'password-reset': subject = 'Password Reset Test - CheckCle'; htmlBody = `

Password Reset Test

This is a test of the password reset template.

If you received this email, your SMTP configuration is working correctly.

Template: Password Reset Email

Collection: ${data.collection || '_superusers'}


Sent from CheckCle Monitoring System

`; break; case 'email-change': subject = 'Email Change Confirmation Test - CheckCle'; htmlBody = `

Email Change Confirmation Test

This is a test of the email change confirmation template.

If you received this email, your SMTP configuration is working correctly.

Template: Email Change Confirmation


Sent from CheckCle Monitoring System

`; break; } return { subject, htmlBody }; }; export const testEmail = async (data: any): Promise => { console.log('testEmail function called with data:', data); try { // Validate required fields if (!data || typeof data !== 'object') { console.log('Invalid request data - not object'); return { status: 200, json: { success: false, message: 'Invalid request data' }, }; } if (!data.email || typeof data.email !== 'string') { console.log('Email address missing or invalid type'); return { status: 200, json: { success: false, message: 'Email address is required and must be a string' }, }; } if (!validateEmail(data.email)) { console.log('Invalid email format:', data.email); return { status: 200, json: { success: false, message: 'Invalid email address format' }, }; } console.log('Email validation passed for:', data.email); const headers = getAuthHeaders(); const baseUrl = getBaseUrl(); // Get current SMTP settings first console.log('Fetching SMTP settings from:', `${baseUrl}/api/settings`); const settingsResponse = await fetch(`${baseUrl}/api/settings`, { method: 'GET', headers, }); if (!settingsResponse.ok) { console.error('Failed to get SMTP settings, status:', settingsResponse.status); return { status: 200, json: { success: false, message: 'Failed to get SMTP settings' }, }; } const settingsData = await settingsResponse.json(); console.log('Retrieved settings data:', settingsData); const smtpSettings = settingsData?.smtp; if (!smtpSettings || !smtpSettings.enabled) { console.log('SMTP not enabled or missing'); return { status: 200, json: { success: false, message: 'SMTP is not enabled. Please enable and configure SMTP settings first.' }, }; } if (!smtpSettings.host || !smtpSettings.username) { console.log('SMTP configuration incomplete - missing host or username'); return { status: 200, json: { success: false, message: 'SMTP configuration is incomplete. Please check host and username.' }, }; } // Create test email content based on template const template = data.template || 'basic'; const { subject, htmlBody } = createEmailTemplate(template, data); console.log('Test email prepared successfully:', { to: data.email, subject: subject, template: template, smtpHost: smtpSettings.host, smtpPort: smtpSettings.port || 587 }); // Send actual email using the correct PocketBase API endpoint console.log('Sending actual email via PocketBase...'); // Fix the payload structure to match PocketBase API expectations const emailPayload = { email: data.email, // Use 'email' instead of 'to' template: template, // Add the template field subject: subject, html: htmlBody, }; console.log('Email payload:', emailPayload); const emailResponse = await fetch(`${baseUrl}/api/settings/test/email`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json', }, body: JSON.stringify(emailPayload), }); if (!emailResponse.ok) { console.error('Failed to send email, status:', emailResponse.status); const errorText = await emailResponse.text(); console.error('Email send error response:', errorText); return { status: 200, json: { success: false, message: 'Failed to send email. Please check your SMTP configuration.' }, }; } // Handle 204 No Content response (successful but no body) if (emailResponse.status === 204) { console.log('Email sent successfully (204 No Content)'); return { status: 200, json: { success: true, message: `Test email sent successfully to ${data.email}`, }, }; } // For other successful responses, try to parse JSON const emailResult = await emailResponse.json(); console.log('Email sent successfully:', emailResult); return { status: 200, json: { success: true, message: `Test email sent successfully to ${data.email}`, }, }; } catch (error) { console.error('Error in testEmail function:', error); return { status: 200, json: { success: false, message: error instanceof Error ? error.message : 'Failed to send test email. Please check your SMTP configuration.' }, }; } };