VPN技术 · 2023年11月10日 0

Node.js 发送电子邮件

使用Node.js发送电子邮件

通过Nodemailer模块发送邮件

Nodemailer模块能够快速且简便地发送电子邮件。

首先需要安装该模块:

C:UsersYour Name>npm install nodemailer

以下是使用谷歌账号发送邮件的示例:

var nodemailer = require(nodemailer);
var transporter = nodemailer.createTransport({
service: gmail,
auth: {
user: [email protected],
pass: yourpassword
}
});
var mailOptions = {
from: [email protected],
to: [email protected],
subject: Sending Email using Node.js,
text: That was easy!
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log(Email sent: + info.response);
}
});

若需要发送给多个接收者,可以如下操作:

var nodemailer = require(nodemailer);
var transporter = nodemailer.createTransport({
service: gmail,
auth: {
user: [email protected],
pass: yourpassword
}
});
var mailOptions = {
from: [email protected],
to: [email protected],
subject: Sending Email using Node.js,
text: That was easy!
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log(Email sent: + info.response);
}
});

如果希望发送HTML格式的邮件,可以使用以下方式:

var mailOptions = {
from: youremail@gmail.com,
to: [email protected],
subject: Sending Email using Node.js,
html: <h1>Welcome</h1><p>That was easy!</p>
}