使用nodejs发送电子邮件

版权声明:本文为迟思堂主人李迟原创文章,版权所有。可随便任意使用(包括学习研究商用),但由此带来的成果或后果,概与作者无关。胡乱修改的,不注明出处的,概不负责。 https://blog.csdn.net/subfate/article/details/86491051

电子邮件在日常工作中有很大用途,凡项目或任务,有邮件来往可避免扯皮背锅(是否背锅,取决于人,而非邮件)。
而在一些自动化的应用场合,也使用得广泛,特别是系统监控方面,如果在资源使用达到警戒线之前自动发邮件通知运维人员,能消除隐患于前期,而不至于临时临急去做善后方案。
对于多人协合(不管是不是异地)场合,邮件也有用武之地,当有代码或文档更新时,自动发邮件通知项目成员或领导,让各方人员知晓并及时更新(是否更新,取决于人,而非工具)。
说到发邮件,不得不提用程序的方式实现。笔者之前已经开通了腾讯免费企业邮箱,并关联自己的域名,自己注册了些邮箱来测试。

本文使用nodejs语言实现发送电子邮件。

实现

nodejs拥有大量的库,非常方便使用,发送邮件使用了nodemailer库,参考例程,实现了发送功能,源码文件emailtest.js如下:

/*
npm i nodemailer
使用:

*/
const nodemailer  = require("nodemailer");

// 参数:发件人,收件人,主题,正文(支持html格式)
function sendMail(from, aliasName, tos, subject, msg)
{
    const smtpTransport = nodemailer.createTransport({
    host: 'smtp.exmail.qq.com',
    secureConnection: true, // use SSL
    secure: true,
    port: 465,
    auth: {
        user: from,
        pass: '1qaz@WSX',
    }
    });

    smtpTransport.sendMail({
        //from    : '标题别名 <[email protected]>',
        from    : aliasName + ' ' + '<' + from + '>',
        //'[email protected], [email protected]',//收件人邮箱,多个邮箱地址间用英文逗号隔开
        to      : tos,
        subject : subject,//邮件主题
        //text    : msg,
        html    : msg
    }, function(err, res) {
        if (err)
        {
            console.log('error: ', err);
        }
    });
}

function nl2br(str, isXhtml) {
    var breakTag = (isXhtml || typeof isXhtml === 'undefined') ? '<br />' : '<br>';
    var str = (str + '').replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
};

function main()
{
    sendMail('[email protected]', 'nodejs机器人', "[email protected], [email protected]", 
            '这是邮件标题',
            '这是正文。<h2> 我的主页:</h2> 地址为:<a href= www.latelee.org" target="_blank">www.latelee.org</a></br>');
}

// call main
main();

测试

安装依赖包:

npm install nodemailer

运行程序:

node emailtest.js

小结

不同语言有不同的实现细节,但总是能达到目的。结综合考虑,最终决定使用nodejs来实现。后续将扩展这个功能。

李迟 2019.1.15 中午

猜你喜欢

转载自blog.csdn.net/subfate/article/details/86491051