用nodemailer发送email

功能介绍

利用nodemailer开发,调用第三方smtp服务器发送右键(这篇文章将以QQ邮箱作为例子)。


申请授权码

  1. 访问QQ邮箱并登录
  2. 设置 - 账户 - POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
    设置 - 账户
    获取授权码

代码分析

'use strict';
const nodemailer = require('nodemailer');

// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
nodemailer.createTestAccount((err, account) => {
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        host: 'smtp.qq.com',//QQ邮箱的SMTP服务器
        port: 587,//QQ邮箱的SMTP服务器的端口为465或587
        secure: false, // true for 465, false for other ports
        auth: {
            user: ***, // 刚刚申请授权码的邮箱账号
            pass: *** // 刚刚申请的授权码
        }
    });

    // setup email data with unicode symbols
    let message = {
        from: '***', // 这里必须是刚刚申请授权码的邮箱账号
        to: '***', // 收件邮箱
        subject: 'Hello ✔', // Subject line
        text: 'Hello world?', // plain text body
        html: '<b>Hello world?</b>' // html body
    };

    // send mail with defined transport object
    transporter.sendMail(message , (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        // Preview only available when sending through an Ethereal account
        console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

        // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
        // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
    });
});

message参数

  • from : 发件人邮箱
  • to : 收件人邮箱
  • subject : 邮件主题
  • text : 文本格式的邮件内容
  • html : html格式的邮件内容
  • attachments : 附件

更多参数,可参考Message configuration


附件

在message的参数中的attachments中,可添加邮件中想附带的附件。

attachment参数解析:

  • filename : 上传到服务器后的附件的名称
  • path : 附件所在路径

更多参数,可参考Attachments


注意事项

  1. 初始化smtp的transport的账号与发送邮箱的发件人邮箱必须是同一个,否则会报错
  2. 初始化smtp的transport的密码必须是刚刚提到的申请的授权码,不是QQ密码
  3. 如果调用的第三方smtp服务器不是QQ邮箱的,host需要更新第三方提供的地址作对应的修改,端口也是,如163邮箱的smtp服务器地址为 smtp.163.com,端口为465或994
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值