发布时间:2025-12-11 01:38:33 浏览次数:3
要在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 portsauth: {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命令进行安装。
在代码中,需要替换host、port、user、pass、from和to等字段为实际的邮箱服务器和账号信息。