import nodemailer from "nodemailer";
interface MailOptions {
to: string;
subject: string;
text?: string;
html?: string;
}
export class EmailUtil {
private static readonly transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASSWORD,
},
});
public static async sendEmail(options: MailOptions): Promise<void> {
const mailOptions: nodemailer.SendMailOptions = {
from: process.env.EMAIL_USER,
to: options.to,
subject: options.subject,
};
if (options.text) {
mailOptions.text = options.text;
}
if (options.html) {
mailOptions.html = options.html;
}
try {
await this.transporter.sendMail(mailOptions);
console.log(`Email sent to ${options.to}: ${options.subject}`);
} catch (error) {
console.error(`Error sending email to ${options.to}: ${error}`);
}
}
}
使用方法
//使用方法
await EmailUtil.sendEmail({
to: "recipient@example.com",
subject: "Test Email",
text: "This is a test email.",
});