Node.js 中发送带有附件的邮件可以通过使用 nodemailer
库来实现。以下是关于这个问题的基础概念、优势、类型、应用场景以及如何解决问题的详细解答。
nodemailer
提供了简洁的 API 接口。以下是一个使用 nodemailer
发送带有附件的邮件的示例代码:
const nodemailer = require('nodemailer');
const fs = require('fs');
// 创建一个SMTP传输对象
let transporter = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: 'your_email@example.com',
pass: 'your_password'
}
});
// 邮件选项
let mailOptions = {
from: '"Your Name" <your_email@example.com>',
to: 'recipient@example.com',
subject: 'Test Email with Attachment',
text: 'This is a test email with an attachment.',
attachments: [
{
filename: 'example.txt',
path: './example.txt' // 文件路径
},
{
filename: 'image.jpg',
path: './image.jpg', // 文件路径
cid: 'unique_image_id' // 可用于在HTML中引用图片
}
],
html: '<p>This is a test email with an attachment.</p><img src="cid:unique_image_id">'
};
// 发送邮件
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
});
通过上述信息,你应该能够理解如何在Node.js中使用nodemailer
发送带有附件的邮件,并解决可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云