邮箱服务 ---nodemailer 、js-yaml
使用nodejs 发送邮件
需要用到两个库
npm install js-yaml
npm install nodemailer
YAML(YAML Ain't Markup Language)是一种人类可读的数据序列化格式,用于表示数据结构。它通常用于配置文件、数据交换和设置等场景。
主要特点:
- 简洁易读:YAML 使用缩进表示层级关系,不需要大量的标点符号,简洁且易于理解。
- 层级结构:通过缩进表示嵌套结构。
- 支持数据类型:支持字符串、数字、布尔值、列表、字典等数据类型。
- 便于与编程语言交互:YAML 能够轻松与多种编程语言进行交互,如 Python、Ruby、JavaScript 等。
name: John Doe age: 30 address: street: 123 Main St city: Anytown zip: 12345 friends: - Jane - Alice - Bob
在这个例子中,name
和age
是基本的键值对,address
是一个字典,friends
是一个列表。通过缩进,YAML 能清晰地表示层级关系
mailInfo.yaml
pass: 授权码 | 密码
user: xxxxx@qq.com 邮箱账号
index.js
import nodemailer from "nodemailer"; import yaml from "js-yaml"; import fs from "fs"; import http from "http"; import url from "url"; const mailInfo = yaml.load(fs.readFileSync("./mailInfo.yaml", "utf8")); //初始化邮件服务 const transport = nodemailer.createTransport({ service: "qq", host: "smtp.qq.com", port: 465, secure: true, auth: { user: mailInfo.user, pass: mailInfo.pass, }, }); http .createServer((req, res) => { const { pathname } = url.parse(req.url, true); const { method } = req; if (method == "POST" && [pathname == "/send/mail"]) { //发送邮件 let data = ""; req.on("data", (chunk) => { data += chunk; }); req.on("end", () => { const { to, subject, text } = JSON.parse(data); transport.sendMail({ to, //: "收件人", from: mailInfo.user, subject, //: "邮件主题", text, //: "邮件内容", }); res.end("success"); }); } }) .listen(3000, () => { console.log("server is running at port 3000"); });
mail.http
POST http://localhost:3000/send/mail HTTP/1.1 Content-Type: application/json { "to": "xxx@163.com", "subject": "Test", "text": "Hello World!" }