📜 Node 发送邮件

安装

npm install nodemailer --save
1

在自己的邮箱开启 STMP ,然后获取授权码。

初始化

async function createAccount() {
  // const testAccount = await nodemailer.createTestAccount();

  const transporter = nodemailer.createTransport({
    // 使用了内置传输发送邮件 查看支持列表:https://nodemailer.com/smtp/well-known/
    service: "qq",
    port: 465,
    secureConnection: true, // 使用了 SSL
    auth: {
      user: "694666422@qq.com", // 发送方邮箱的账号
      pass: "bkhjixrgfumfbbai", // 邮箱授权密码
    },
  });

  return transporter;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

可以直接使用的邮件服务器[列表](WELL-KNOWN SERVICES)

然后就可以准备发送代码了

async function send(info) {
  if (!info) throw new Error("邮件信息异常,发送失败。");

  const { to, subject, text } = info;

  if (!to || !subject || !text) throw new Error("邮件信息不全,发送失败。");

  const transporter = await createAccount();

  return await transporter.sendMail({
    from: `"qins" <694666422@qq.com>`,
    to,
    subject,
    text,
  });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

完整 Demo 代码

"use strict";
const nodemailer = require("nodemailer");

async function createAccount() {
  // const testAccount = await nodemailer.createTestAccount();

  const transporter = nodemailer.createTransport({
    service: "qq",
    port: 465,
    secureConnection: true, // 使用了 SSL
    auth: {
      user: "694666422@qq.com", // 发送方邮箱的账号
      pass: "bkhjixrgfumfbbai", // 邮箱授权密码
    },
  });

  return transporter;
}

async function send(info) {
  if (!info) throw new Error("邮件信息异常,发送失败。");

  const { to, subject, text } = info;

  if (!to || !subject || !text) throw new Error("邮件信息不全,发送失败。");

  const transporter = await createAccount();

  return await transporter.sendMail({
    from: `"qins" <694666422@qq.com>`,
    to,
    subject,
    text,
  });
}

send({
  to: "qinsjs@dingtalk.com",
  subject: "测试邮件发送 | subject",
  text: "测试邮件发送 | text",
})
  .then(console.log)
  .catch(console.error);
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

参考文献