node发送邮件

2024-02-20  本文已影响0人  姜治宇
const fs = require('fs');
const nodemailer = require('nodemailer'); // 引入 nodemailder
const xlsx = require('node-xlsx');
//邮箱信息
const mailUser = 'abc@163.com';
const mailPass = 'xxxxxxxxxxxx';
//待发送的邮箱
const liststr = fs.readFileSync('./mail_release.json', 'utf-8');
const list = JSON.parse(liststr);
let Email_QQ = {
    // 以 QQ 邮箱为例子代码如下,如需配置其他邮箱,可查看文章第三点 nodemailer 各邮箱相关配置 
    host: 'smtp.163.com',
    port: 465,
    secure: true,
    maxConnections: 3,
    pool: true,
    auth: {
        user: mailUser, // 发送人邮箱
        // 这里是 stmp 授权码,并非邮箱密码,
        // 如未开通 stmp 请查阅 https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
        pass: mailPass
    }
}
// 创建发送邮件服务 nodemailer 对象,传入 QQ 设置,当然你也可以开发接口从前端传入不同的 user 和对应的 pass
let transporter = nodemailer.createTransport(Email_QQ);
sendAction();
function sendAction(){
    doSend(list.data);
}

function doSend(arr) { //给有排名的用户发送邮件
    
    arr.map(async (v) => {

        const mail = v.userEmail;
        const rank = v.rank;
        const content = getContent(rank);
        await sendEMail(mail, content);

    });
}

//邮件模板
function getContent(rank) {
    return `<h3>Dear Participants,</h3>
    <p style="text-align:justify;line-height:24px;">
    Thanks for your participation,your rank is ${rank}.... 
    </p> 
    <p>Best regards,</p>
    <p>
    your friend...
    </p>
    `;
}
//发送邮件
function sendEMail(mail, text) {
    // 邮件的相关信息
    let msg = {
        from: mailUser, // 发送人邮箱
        to: mail, // 接收者邮箱,多个邮箱用逗号间隔

        subject: 'Congratulations on Winning Prizes in the AI Powered Flood Mapathon!', // 邮件标题

        // text: '纯文本内容。。。', // text 和 html 属性二选一
        html: text // html 文本内容,可以添加 html 元素
    }

    // 发送邮件
    return new Promise(resolve => {
        transporter.sendMail(msg, (err, res) => {

            if (res) {
                let len = res.accepted.length
                let from = res.envelope.from
                console.log('已从' + from + '邮箱成功发出' + len + '个邮件');
                resolve(true);
            } else {
                console.log('err : ', err)
                resolve(false);
            }
        })
    });

}

上一篇下一篇

猜你喜欢

热点阅读