邮件收发

发送邮件

Copy
import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
service: 'QQ',
auth: {
user: 'xxx@qq.com',
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('邮件发送完成')
}
});
}

接收邮件

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

var imap = new Imap({
user: "xx@qq.com",
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;
};