Alex-Programer

Alex-Programer

随缘博客,不定期更新不确定的内容~
github
twitter

郵件收發

發送郵件#

import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
  service: 'QQ',
  auth: {
    user: '[email protected]',
    pass: 'xxx'
  }
});

const send = (text: string, link: string) => {
  let mailOptions = {
    from: '發件人',
    to: ["收件人"],
    subject: '副標題',
    html: ""
  };

  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      console.error(err);
    } else {
      console.log('郵件發送完成')
    }
  });
}

接收郵件#

const Imap = require("imap");
const { MailParser } = require("mailparser");

var imap = new Imap({
  user: "[email protected]",
  password: "xx",
  host: "imap.qq.com",
  port: 993,
  tls: true,
  tlsOptions: { rejectUnauthorized: false },
});


const receive = async () => {
  const lastMessage = await new Promise((resolve) => {
    let lastMessageText = "";

    function openInbox(cb) {
      imap.openBox("INBOX", true, cb);
    }

    imap.once("ready", function () {
      openInbox(function (err, box) {
        if (err) throw err;

        // 獲取今天所有的郵件。(無法精確到時分秒)
        imap.search(["ALL", ["SINCE", Date.now()]], function (err, results) {
          if (err) throw err;
          var f = imap.fetch(results, { bodies: "" });

          f.on("message", function (msg, seqno) {
            var mailparser = new MailParser();

            msg.on("body", function (stream) {
              stream.pipe(mailparser);

              mailparser.on("data", function (data) {
                if (data.type === "text" && data.text) // 接收文字(還可以是圖片)
                  lastMessageText = data.text;
              });
            });
          });

          f.once("end", function () {
            imap.end();
          });
        });
      });
    });

    imap.once("error", function (err) {
      console.log(err);
    });

    imap.once("end", function () {
      resolve(lastMessageText);
    });

    imap.connect();
  });

  return lastMessage;
};

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。