温馨提示×

js发邮件功能怎么实现

js
小亿
128
2023-07-17 13:53:02
栏目: 编程语言

要在JavaScript中实现发送邮件的功能,可以使用SMTP协议来发送邮件。以下是一个使用SMTP协议发送邮件的示例代码:

const nodemailer = require('nodemailer');
// 创建一个SMTP传输对象
const 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'
}
});
// 邮件内容
const mailOptions = {
from: 'your_email@example.com',
to: 'recipient@example.com',
subject: 'Hello from Node.js',
text: 'Hello, this is a test email from Node.js'
};
// 发送邮件
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});

请注意,上述代码使用了nodemailer库来实现邮件发送功能。在使用之前,需要先安装nodemailer库,可以通过npm install nodemailer命令进行安装。

在代码中,需要替换hostportuserpassfromto等字段为实际的邮箱服务器和账号信息。

0