--- title: 'node如何发生邮件,nodemailer' date: 2021-08-10 15:35:00 --- ![](https://img-blog.csdnimg.cn/20210810152919473.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3h1dG9uZ2Jhbw,size_16,color_FFFFFF,t_70) ```javascript const nodemailer = require("nodemailer") let transporter const emailInit = async () => { // Generate test SMTP service account from ethereal.email // Only needed if you don't have a real mail account for testing let testAccount = await nodemailer.createTestAccount(); // create reusable transporter object using the default SMTP transport transporter = nodemailer.createTransport({ host: 'smtp.sina.cn', // service: 'qq', // port: 465, //secure: false, // true for 465, false for other ports secureConnection: true, // 使用了 SSL auth: { user: '136xxxxx@sina.cn', // generated ethereal user pass: '密码' // generated ethereal password } }); } emailInit() //发送邮件 // async..await is not allowed in global scope, must use a wrapper const sendEmail = async (dataObj) => { const { path, username, errorTitle, detail, browser } = dataObj // send mail with defined transport object let info = await transporter.sendMail({ from: '<13642061747@sina.cn>', // sender address to: '1183391880@qq.com', //'1183391880@qq.com', // list of receivers subject: "知了好学错误报告", // Subject line html: ` <div> <div> <span>路径:</span> <a href="http://zlhx.gongzuoshouji.cn/#${path}">${path}</a> </div> <div> <span>用户名:</span> <span>${username}</span> </div> <div> <span>错误标题:</span> <span>${errorTitle}</span> </div> <div> <span>错误详情:</span> <div style="white-space: pre-wrap">${detail}</div> </div> <div> <span>发生时间:</span> <span>${Date()}</span> </div> <div> <span>浏览器型号:</span> <span>${browser}</span> </div> </div>`// html body }); console.log("Message sent: %s", info.messageId); // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com> // Preview only available when sending through an Ethereal account console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info)); // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou... } module.exports = { //发送邮件 sendEmail, } ``` 开发接口,并把接口部署到阿里云上: ```javascript //发送邮件的接口 const dataEmail = async (req, res) => { const emailData = req.body await sendEmail({ ...emailData }).catch((err) => { console.log(err) }) res.send({ state: 1, data: emailData, message: '成功', }) } ``` 在其他node项目中调用阿里云的接口即可发邮件: 例如项目托管在([https://glitch.com/](https://glitch.com/)),这是一个国外的服务器,无法使用国内的邮箱直接发邮件,但是可以调用阿里云上的接口发邮件! ```javascript const axios = require('axios') //调用阿里云服务器上的发送邮件的接口 const emailPost = (emailData) => { axios .post('http://xxx:81/api/log/email', { ...emailData }) .then((res) => { console.log(`statusCode: ${res.statusCode}`) console.log(res) }) .catch((error) => { console.error(error) }) } ```