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;
};

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。