nodemailer实现发送邮件功能

在nodejs项目中,遇到要向某一个邮箱发送邮件时可使用nodemailer,可支持QQ,163,126,Yahoo等等

安装:npm install nodemailer --S

/*
 * @Description: 描述
 * @Version: 1.0
 * @Autor: Nanke_南柯
 * @Date: 2021-10-13 22:52:36
 * @LastEditors: Nanke_南柯
 * @LastEditTime: 2021-10-13 22:57:09
 */
const nodemailer = require('nodemailer');
 
// 开启一个 SMTP 连接池
let transporter = nodemailer.createTransport({
    host: 'smtp.qq.com',
    secureConnection: true, // use SSL
    port: 465,
    secure: true, // secure:true for port 465, secure:false for port 587
    auth: {
        user: 'xxxxxxxxx@qq.com',
        pass: 'xxxxxxxxxx' // QQ邮箱需要使用授权码
    }
});
 
// 设置邮件内容(谁发送什么给谁)
let mailOptions = {
    from: 'xxxxxxxxx@qq.com', // 发件人
    to: 'xxxxxxxxx@qq.com', // 收件人
    subject: '测试发送邮件', // 主题
    // text: '这是一封来自 Node.js 的测试邮件', // plain text body
    html: '<b>这是一封来自 南柯大帅哥 的测试邮件</b>', // html body
    // 下面是发送附件,不需要就注释掉
    // attachments: [{
    //         filename: 'test.md',
    //         path: './test.md'
    //     },
    //     {
    //         filename: 'content',
    //         content: '发送内容'
    //     }
    // ]
};
 
// 使用先前创建的传输器的 sendMail 方法传递消息对象
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log(`Message: ${info.messageId}`);
    console.log(`sent: ${info.response}`);
});

 

posted @ 2021-10-15 12:37  南柯Dream丶  阅读(41)  评论(0)    收藏  举报