on email tab create a test email button to test smtp integration

This commit is contained in:
Leon Serfaty G
2025-07-17 11:22:46 +00:00
parent 6a1d37bdc7
commit 9a4ec2a118
4 changed files with 201 additions and 72 deletions
+65
View File
@@ -0,0 +1,65 @@
'use server';
import nodemailer from 'nodemailer';
import { z } from 'zod';
const emailSettingsSchema = z.object({
smtpHost: z.string(),
smtpPort: z.number(),
smtpUsername: z.string(),
smtpPassword: z.string(),
fromName: z.string(),
fromEmail: z.string().email(),
});
type EmailSettings = z.infer<typeof emailSettingsSchema>;
export async function sendTestEmail(
settings: EmailSettings
): Promise<{ success: boolean; error?: string }> {
const { smtpHost, smtpPort, smtpUsername, smtpPassword, fromName, fromEmail } = settings;
try {
const transporter = nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpPort === 465, // true for 465, false for other ports
auth: {
user: smtpUsername,
pass: smtpPassword,
},
// In a real app, you might want more robust TLS options
// For example, rejecting unauthorized connections
tls: {
rejectUnauthorized: false
}
});
await transporter.verify();
const mailOptions = {
from: `"${fromName}" <${fromEmail}>`,
to: fromEmail, // Send the test to the 'from' address
subject: 'SMTP Test Email from EstimateFlow',
text: 'This is a test email to verify your SMTP settings. If you received this, your configuration is correct.',
html: '<p>This is a test email to verify your SMTP settings. If you received this, your configuration is correct.</p>',
};
await transporter.sendMail(mailOptions);
return { success: true };
} catch (error: any) {
console.error('Failed to send test email:', error);
// Provide a more user-friendly error message
let errorMessage = 'An unknown error occurred.';
if (error.code === 'ECONNREFUSED') {
errorMessage = `Connection refused. Check if the SMTP host (${smtpHost}) and port (${smtpPort}) are correct and accessible.`;
} else if (error.code === 'EAUTH') {
errorMessage = 'Authentication failed. Please check your SMTP username and password.';
} else if (error.message) {
errorMessage = error.message;
}
return { success: false, error: errorMessage };
}
}