LQ博客 www.lqblogs.com
arrows
nav

nodemailer 邮件发送组件

作者:lq 来源:原创 发布时间:2019-07-23 浏览量:2574 评论:0 点赞:45

在很多项目中,我们都会遇到邮件注册,邮件反馈等需求。在node中收发电子邮件也非常简单,因为强大的社区有各种各样的包可以供我么直接使用。Nodemailer包就可以帮助我们快速实现发送邮件的功能。本文章将结合QQ邮箱进行实战演练。

Nodemailer是一个简单易用的Node.js邮件发送组件

官网地址:https://nodemailer.com

GitHub地址:https://github.com/nodemailer/nodemailer

Nodemailer的主要特点包括:

  • 支持Unicode编码

  • 支持Window系统环境

  • 支持HTML内容和普通文本内容

  • 支持附件(传送大附件)

  • 支持HTML内容中嵌入图片

  • 支持SSL/STARTTLS安全的邮件发送

  • 支持内置的transport方法和其他插件实现的transport方法

  • 支持自定义插件处理消息

  • 支持XOAUTH2登录验证

首先,我们肯定是要下载安装 注意:Node.js v6+   

npm install nodemailer --save

结合QQ邮箱实战案例:

直接复制当前主体内容,或复制全部内容当做模块文件来使用。

"use strict";
const nodemailer = require("nodemailer");
// async..await is not allowed in global scope, must use a wrapper
async function main(){

  // Generate test SMTP service account from ethereal.email
  const transporter = nodemailer.createTransport({
        // host: 'smtp.ethereal.email',
        service: 'QQ',//使用了内置传输发送邮件 查看支持列表
        port: 465,
        secureConnection: true,
        auth: {
            user: 'xxxxxxxxx@qq.com',//使用了 SSL
            pass: 'xxxxxxxxxxxxx',//这里为qq邮箱的授权码,参照下面qq截图
        }
    });
   // verify connection configuration
    transporter.verify(function(error, success) {
      if (error) {
        console.log(error);
      } else {
        console.log("Server is ready to take our messages");
      }
    });
    try {
        //send mail with defined transport object
        let info = await transporter.sendMail({
            from: '"hello"', // sender address
            to: 'xxxxxxxxx@qq.com', // list of receivers
            subject: "Hello world", // Subject line
            // text: "Hello world?", // plain text body
            html: "Hello world?", // html body
        });
        console.log("Message sent: %s", info.messageId);
        return {status:true};
    } catch(e) {
        // statements
        return {status:false, msg: '发送邮箱失败:'+e.response};
    }
  // Message sent:// Preview only available when sending through an Ethereal account
  // console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

// main().catch(console.error);

module.exports = main;

参照下面图片示例步骤进行操作获取QQ邮箱授权码:

(1)进入qq邮箱后,点击"设置">>"帐户"

(2)在帐户选项页找到"帐户安全">>"POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务"

(3)前两种随便选择一种,点击"开启",然后进行相应发送短信操作,发送成功后,点击"已发送",就可以看到你想要的授权码了

4%2)U39$HP$LQ@M~W3__V`C

L1SGFP3LJ02KFXLES9K`[KM

S(%59YSC94FKC]%R}~CWSCL

nodemailer node
如果你感觉本文章对你有帮助的话,那就点赞、打赏或订阅一下吧
点赞(45)
打赏
倒踩(0)
关闭 感谢您的支持,我会继续努力
微信支付
支付宝支付
扫码打赏,建议金额1-20元
浏览量(2574)
讨论本篇文章(0)
发表评论

最多访问文章

最新文章