Node项目中实现发送邮件功能

用到的插件nodemailer

插件地址icon-default.png?t=N7T8https://community.nodemailer.com/

实现流程

1.下载nodemailer

2. 在node中创建js文件

3. 在项目中引入nodemailer

// 发送邮件
const  nodemailer = require('nodemailer');
const  fs =require('fs')

4. 使用自带的发送邮件功能填入对应参数

// 发送邮件
let  transporter = nodemailer.createTransport({
 host:  '',
 port:  '',
 secure:  true, // true465, false其他端口
 auth: {
 user:  '',
 pass:  '',
  },
});
  • host: 您的SMTP服务器主机名。
  • port: 您的SMTP服务器端口号。常见的端口号是465(使用SSL)或587(使用STARTTLS)。
  • user: 您的发件人邮箱地址。
  • pass: 这里填写的是授权码
获取以上内容:

SMTP服务器主机名,端口号,授权码的获取均在qq邮箱—设置—账户—POP3/IMAP/SMTP/Exchange/CardDAV 服务—开启服务

5. 将图片转为base64形式(不转发送不成功)

const  imagePath = './github.png';
const  imageBuffer = fs.readFileSync(imagePath);
const  base64Image = imageBuffer.toString('base64');
console.log(base64Image,'转为base64的图片');

6. 设置电子邮件选项

// 设置电子邮件选项
let  mailOptions = {
 from:  '',
 to:  '',
 subject:  '',
 text:  '',
 html:  ``,
//注释的内容是要发送附件的内容
 // attachments: \[
 //   {
 //     filename: 'image\_file\_name',  .//名字
 //     content: './github.png',  //附件内容
 //   },
 // \],
};
  • from: 发件人邮箱地址。
  • to 收件人邮箱地址。
  • subject: 您要发送的邮件主题。
  • text: 您要发送的邮件内容。

7. 发送电子邮件

// 使用传输器对象发送电子邮件
transporter.sendMail(mailOptions, function (error, info) {
 if (error) {
 console.log(error);
} else {
 console.log('邮件已发送: ' + info.response);
  }
});

猜你喜欢

转载自blog.csdn.net/m0_65465945/article/details/135976807