天天看点

node.js 使用nodemailer发送qq邮件

实现nodemailer发送邮件给qq邮箱

安装环境

这里分享笔者的版本,各位可以根据需求更改

  • node – 10.15.3
  • express – 4.16.4
  • nodemailer --6.1.0

注意:笔者只使用了一个index.js文件,以下代码合并在一个页面后即可运行.可以根据个人需求分页开发

配置传送服务

let mailTransport = nodemailer.createTransport({
    // host: 'smtp.qq.email',
    service:'qq',
    secure: true,	//安全方式发送,建议都加上
    auth: {
        user: '[email protected]',
        pass: '*************'
    }
})
           
  • 配置中的auth用于配置用于发送邮件的邮箱,这里使用的是qq邮箱
  • user即你的qq邮箱地址,xxxxxxxx表示qq号
  • 注意,这里的pass并不是你的qq密码,而是在qq邮箱中开启SMTP服务时提供的授权码,具体开启步骤如下

开启QQ邮箱SMTP

  • 登录QQ邮箱
  • 点击左上角设置
  • 选择账户栏往下翻
  • 有一个POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务栏,选择IMAP/SMTP服务开启选项,如图.记得记录给你的授权码,填入pass
    node.js 使用nodemailer发送qq邮件

引入需要的模块并开启app

let nodemailer = require('nodemailer');
let express = require('express');
let app = express();

           

建立访问地址

app.get('/send',function(req,res) {
    let options = {
        from: ' "zhy" <[email protected]>',
        to: '<[email protected]>',
        bcc: '密送',
        subject: 'node邮件',
        text: 'hello nodemailer',
        html: '<h1>hello zhy</h1>'
    };
    mailTransport.sendMail(options,function(err,msg) {
        if(err) {
            console.log(err);
            res.send(err);
        } else {
            res.send('success');
        }
    })
});
           
  • from表示发送方,也就是你的邮箱,zhy表示名称,选择性填写
  • to表示接收方,也就是想要发送给谁
  • subject是邮件标题
  • text是邮件内容,如果包含html会被覆盖
  • html以html后的内容显示在邮件正文

监听端口

app.listen(8000,function() {
    console.log('running...');
})
           

接下来就可以通过开启服务并访问localhost:8000/send来发送邮件了,可以到接收方邮箱中查看

node.js 使用nodemailer发送qq邮件

继续阅读