使用Node.js還可以發(fā)郵件

前言

今天,我們給大家開發(fā)一個小效果。篇幅比較短,主要給大家展示效果。
實戰(zhàn)

    首先我們初始化一個Node項目

    npm init -y


    創(chuàng)建一個app.js文件

    'use strict';

    const nodemailer = require('nodemailer');

    let transporter = nodemailer.createTransport({
      // host: 'smtp.ethereal.email',
      service: 'qq', // 使用了內(nèi)置傳輸發(fā)送郵件 查看支持列表:https://nodemailer.com/smtp/well-known/
      port: 465, // SMTP 端口
      secureConnection: true, // 使用了 SSL
      auth: {
        user: 'xxx@qq.com', // 這里以QQ郵箱為例
        pass: 'kzudmlwerknibejc', // 設(shè)置的smtp授權(quán)碼
      }
    });

    let mailOptions = {
      from: '"xxx" <xxx@qq.com>', // sender
      to: 'xxx@163.com', // receivers
      subject: 'Hello', // Subject line
      // 發(fā)送text或者h(yuǎn)tml格式
      // 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);
      // Message sent: <04ec7731-cc68-1ef6-303c-61b0f796b78f@qq.com>
    });


    Nodemailer是一個簡單易用的Node.js郵件發(fā)送組件。

    官網(wǎng)地址:https://nodemailer.com

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

    Nodemailer的主要特點包括:

        支持Unicode編碼

        支持Window系統(tǒng)環(huán)境

        支持HTML內(nèi)容和普通文本內(nèi)容

        支持附件(傳送大附件)

        支持HTML內(nèi)容中嵌入圖片

        支持SSL/STARTTLS安全的郵件發(fā)送

        支持內(nèi)置的transport方法和其他插件實現(xiàn)的transport方法

        支持自定義插件處理消息

        支持XOAUTH2登錄驗證

    獲取smtp授權(quán)碼

    登錄QQ郵箱,點擊郵箱設(shè)置。

找到如下圖紅框所示,開啟IMAP/SMTP服務(wù)后,就可以隨機獲取授權(quán)碼了。

    啟動項目

    node app.js


優(yōu)化

    可以使用node-schedule來創(chuàng)建定時任務(wù)

    npm install node-schedule


    單位時間段可以執(zhí)行代碼發(fā)送郵件。

作者:Vam的金豆之路

主要領(lǐng)域:前端開發(fā)

我的微信:maomin9761

微信公眾號:前端歷劫之路