insurance-spider/mailer.js

101 lines
2.7 KiB
JavaScript

import nodemailer from "nodemailer";
import path from "path";
class EmailSender {
constructor(config) {
this.transporter = nodemailer.createTransport(config);
this.defaultFrom = config.auth.user;
}
async sendEmail(options) {
try {
const mailOptions = {
from: options.from || this.defaultFrom,
to: options.to,
cc: options.cc,
bcc: options.bcc,
subject: options.subject,
text: options.text,
html: options.html,
attachments: options.attachments || [],
};
const info = await this.transporter.sendMail(mailOptions);
console.log(`邮件发送成功: ${options.to} - ${info.messageId}`);
return { success: true, messageId: info.messageId };
} catch (error) {
console.error(`邮件发送失败: ${options.to} -`, error.message);
throw error;
}
}
async sendBasicEmail(to, subject, content) {
return await this.sendEmail({ to, subject, html: content });
}
async sendEmailWithAttachments(to, subject, content, attachmentPath) {
const attachments = [];
if (attachmentPath) {
attachments.push({
filename: path.basename(attachmentPath),
path: attachmentPath,
});
}
return await this.sendEmail({ to, subject, html: content, attachments });
}
async sendBulkEmail(recipients, subject, content) {
const results = [];
for (const recipient of recipients) {
try {
const result = await this.sendEmail({
to: recipient,
subject,
html: content,
});
results.push({ recipient, success: true, result });
} catch (error) {
results.push({ recipient, success: false, error: error.message });
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
return results;
}
async testConnection() {
try {
await this.transporter.verify();
console.log("邮件服务器连接成功");
return true;
} catch (error) {
console.error("邮件服务器连接失败:", error);
return false;
}
}
}
// async function example() {
// let emailSender = new EmailSender({
// host: "smtp.exmail.qq.com",
// port: 465,
// secure: true,
// auth: {
// user: "jiqiren@axbbaoxian.com",
// pass: "Am13579q",
// },
// });
// const isConnected = await emailSender.testConnection();
// if (!isConnected) {
// console.log("邮件服务器连接失败");
// return;
// }
// emailSender.sendBasicEmail(
// "cpw@axbbaoxian.com",
// "测试邮件",
// "这是测试邮件内容"
// );
// }
// example().catch((err) => {
// console.error("程序错误:", err);
// });
export { EmailSender };