on email tab create a test email button to test smtp integration
This commit is contained in:
@@ -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 };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user