面试题答案
一键面试- 安装Nodemailer:
在项目目录下运行
npm install nodemailer
安装Nodemailer模块。 - 配置SMTP服务器信息并发送邮件示例代码:
const nodemailer = require('nodemailer');
// 创建一个SMTP传输对象
let transporter = nodemailer.createTransport({
host: 'smtp.example.com', // SMTP服务器地址
port: 587, // 端口,常见如587, 465等
secure: false, // 如果使用465端口,设置为true
auth: {
user: 'your_email@example.com', // 用户名
pass: 'your_password' // 密码
}
});
// 邮件内容
let mailOptions = {
from: '"Sender Name" <sender@example.com>', // 发件人
to: 'recipient@example.com', // 收件人
subject: 'Hello ✔', // 主题
text: 'Hello world?', // 纯文本内容
html: '<b>Hello world?</b>' // HTML内容
};
// 发送邮件
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
});
上述代码中:
host
配置了SMTP服务器地址。port
配置了连接SMTP服务器的端口。auth.user
和auth.pass
分别配置了用户名和密码。
注意,实际应用中要替换 smtp.example.com
、your_email@example.com
、your_password
、sender@example.com
、recipient@example.com
等为真实信息。同时,不同的邮件服务提供商的SMTP服务器地址、端口等配置可能有所不同,需要根据实际情况调整。