node 收发邮件

发邮件是基于 <u><font style="color:rgb(37, 41, 51);">SMTP</font></u> 协议,收邮件是基于 <u><font style="color:rgb(37, 41, 51);">POP3</font></u><u><font style="color:rgb(37, 41, 51);">IMAP</font></u> 协议。

node 分别有 nodemailer 包和 imap 包用来支持收发邮件的协议。可通过 nodemailer 发送了 html 的邮件,可以发送任何 html+css 的内容。通过 imap 实现了邮件的搜索,然后用 mailparser来做了内容解析,然后把邮件内容和附件做了下载。

生成 QQ 邮件授权码:【virlzuiwzsiojida】

mail-post.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* @script  发送邮件 */
const nodemailer = require("nodemailer");

const transporter = nodemailer.createTransport({
host: "smtp.qq.com",
port: 587,
secure: false,
auth: {
user: "bazijun627@qq.com",
pass: "virlzuiwzsiojida",
},
});

async function main() {
const info = await transporter.sendMail({
from: "bazijun627 <bazijun627@qq.com>",
to: "bazijun627@163.com",
subject: "Hello 小把",
text: "是我",
});

console.log("邮件发送成功:", info.messageId);
}

main().catch(console.error);

mail-receive.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* @script 接收最近邮件*/
const Imap = require("imap");
const { MailParser } = require("mailparser");
const fs = require("fs");
const path = require("path");

const imap = new Imap({
user: "bazijun627@qq.com",
password: "virlzuiwzsiojida",
host: "imap.qq.com",
port: 993,
tls: true,
});

imap.once("ready", () => {
imap.openBox("INBOX", true, (err) => {
imap.search(
[["SEEN"], ["SINCE", new Date().toLocaleString()]],
(err, results) => {
if (!err) {
handleResults(results);
} else {
throw err;
}
}
);
});
});

imap.connect();

function handleResults(results) {
imap
.fetch(results, {
bodies: "",
})
.on("message", (msg) => {
const mailparser = new MailParser();

msg.on("body", (stream) => {
const info = {};
stream.pipe(mailparser);
mailparser.on("headers", (headers) => {
info.theme = headers.get("subject");
info.form = headers.get("from").value[0].address;
info.mailName = headers.get("from").value[0].name;
info.to = headers.get("to").value[0].address;
info.datatime = headers.get("date").toLocaleString();
});

mailparser.on("data", (data) => {
if (data.type === "text") {
info.html = data.html;
info.text = data.text;
// 需要存在 mails 文件夹
const filePath = path.join(
__dirname,
"mails",
info.theme + ".html"
);
fs.writeFileSync(filePath, info.html || info.text);
console.log(info);
}
if (data.type === "attachment") {
// 需要存在 files 文件夹
const filePath = path.join(__dirname, "files", data.filename);
const ws = fs.createWriteStream(filePath);
data.content.pipe(ws);
}
});
});
});
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!