Alex-Programer

Alex-Programer

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

Email Sending and Receiving

Send Email#

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: 'Sender',
    to: ["Recipient"],
    subject: 'Subtitle',
    html: ""
  };

  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      console.error(err);
    } else {
      console.log('Email sent')
    }
  });
}

Receive Email#

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;

        // Get all emails today (cannot be accurate to the hour, minute, and second)
        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) // Receive text (can also be an image)
                  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;
};

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.