关于node.js:使用nodemailer在本地发送邮件

6次阅读

共计 1233 个字符,预计需要花费 4 分钟才能阅读完成。

本文探索了如何利用 nodemailer 库在本地应用 api 的形式来发送电子邮件。

nodemailer 官网

装置

npm install nodemailer -S

根本实现

// @doc https://nodemailer.com/
const nodemailer = require("nodemailer");

async function main() {
  let transporter = nodemailer.createTransport({
    // 反对 465 和 587,二者都能够
    port: 587,
    secure: false, // true for 465, false for other ports
    // port: 465,
    // secure: true,

    // 服务起源:163 邮箱
    service: "163",
    auth: {
      user: "frost@163.com",
      // 邮箱 SMTP 受权码,很重要,相当于一般的邮箱明码
      // @question https://note.youdao.com/ynoteshare1/index.html?id=f9fef46114fb922b45460f4f55d96853&type=note
      pass: "xxx",
    },
  });

  let info = await transporter.sendMail({
    from: '"frost" <frost@163.com>', // sender address
    to: "xx@163.com,xxx@qq.com", // list of receivers
    subject: "Hello ✔", // Subject line
    html: "<b>Hello world2?</b>", // html body
  });

  console.log("Message sent: %s", info.messageId);
}

main().catch(console.error);

间接 node index.js 即可运行,去邮箱查看邮件吧。

这里的邮箱 SMTP 受权码须要在对应的邮箱设置中获取。

163 邮箱 - 如何开启客户端受权码?

增加附件

const path = require("path");

  async function main() {
   let info = await transporter.sendMail({
    // ...
    attachments: [
      {
        filename: "hello.txt",
        content: "hello world",
      },
      {
        filename: "network_image.jpg",
        href: "https://img0.baidu.com/it/u=3212920999,1827079299&fm=26&fmt=auto&gp=0.jpg",
      },
      {
        filename: "local.txt",
        path: path.resolve(__dirname, "local.txt"),
      },
    ],
  });
}

其中第三个文件是在本地新建一个 txt 文件,发现附件曾经带上了。

更多

HTML 模板 -Documentation for MJML

正文完
 0