天天看点

node.js使用 nodemailer 库发送邮件以及EREFUSED问题的出现

在node.js 想要发送邮件 可以加载 nodemailer 库,我们大多数情况使用的都是qq邮箱,所以在开

始写代码之前需要先到 qq邮箱中开启SMTP,并获取SMTP授权码。

获取SMTP授权码

打开qq邮箱 —>设置 —> 账户 —> POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 —>开启SMTP服务并获得授权码

代码如下:

'use strict';

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
    //host: 'smtp.qq.email',
    service: 'qq',
    port: 465, // SMTP 端口
    secureConnection: true, // 使用了 SSL
    auth: {
        user: '你的邮箱',//你的邮箱
        // 这里密码不是qq密码,是你设置的smtp授权码
        pass: '就是农科一开始让大家操作获得SMTP的授权码',
    }
});

let mailOptions = {
    from: '"中北大学教务处"<[email protected]>', // sender address
    to: '[email protected]', // list of receivers
    subject: '标题', // Subject line
    // 发送text或者html格式
    // 只能二选一
    // text: 'Hello world', // plain text body
    html: '<b>'Hello world</b>' // html body
};

// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message sent: %s', info.messageId);
});

           

smtp.qq.emai的问题

1、host: ‘smtp.qq.email’, 不能使用,需要改成service: ‘qq’,如果想要使用前者,需要自己搭建node的HTTP服务,我不太清楚这个是共性还是仅仅是我自己。拿出来给大家分享。

EREFUSED 问题

当时给我报了一个错误,

node.js使用 nodemailer 库发送邮件以及EREFUSED问题的出现

当时学校断网,连接的是自己的手机热点。一晚上没有解决这个问题,当时就怀疑是不是网络的问题,第二天校园网好了,这个问题也解决了。

如果大家也遇到相同的问题,希望可以帮助到大家,如果有其他的问题,也可以放在这里,大家一起解决。共勉~~

继续阅读