nodejs -- 邮箱服务【nodemailer】和【yaml】
**YAML **
YAML(YAML Ain't Markup Language)是一种人类友好的数据序列化格式,广泛用于配置文件(如 Docker Compose、Kubernetes、CI/CD 等)。它比 JSON 更易读,支持注释、多行字符串和复杂数据结构。
1. YAML 基础语法
1.1 基本规则
- 缩进:使用空格(通常 2 或 4 个),不能使用 Tab。
- 键值对:用
:
分隔,冒号后必须有空格。 - 注释:以
#
开头。 - 大小写敏感。
示例:
name: John Doe # 字符串
age: 30 # 数字
is_student: false # 布尔值
1.2 数据类型
类型 | 示例 | 说明 |
---|---|---|
字符串 | name: "Alice" |
可加引号,也可不加 |
数字 | age: 25 |
整数或浮点数 |
布尔值 | active: true |
true /false |
Null | value: null |
表示空值 |
数组 | fruits: [apple, banana] |
使用 [] 或 - 表示列表 |
对象 | person: {name: Bob} |
嵌套结构 |
2. YAML 高级特性
2.1 多行字符串
|
:保留换行符(适合代码块)>
:折叠换行符(适合段落)
示例:
description: |
This is a multi-line
string with line breaks.
summary: >
This is a long sentence
that will be folded into one line.
2.2 数组(列表)
方式 1:使用 -
表示列表项
fruits:
- apple
- banana
- orange
方式 2:行内写法(类似 JSON)
fruits: [apple, banana, orange]
2.3 嵌套对象
person:
name: Alice
age: 28
address:
city: New York
zip: 10001
2.4 锚点(&
)和引用(*
)
用于复用数据:
defaults: &defaults
timeout: 30
retries: 3
service1:
<<: *defaults # 继承 defaults 的所有属性
port: 8080
3. YAML vs. JSON
特性 | YAML | JSON |
---|---|---|
可读性 | 高(支持注释、多行字符串) | 较低(无注释,严格格式) |
用途 | 配置文件、K8s、Docker | API 数据交换、Web 传输 |
扩展名 | .yaml 或 .yml |
.json |
解析 | 需要 YAML 解析器 | 内置 JavaScript 支持 |
JSON 示例:
{
"name": "John",
"age": 30,
"is_student": false
}
等效 YAML:
name: John
age: 30
is_student: false
4. 常见应用场景
4.1 Docker Compose
version: "3.8"
services:
web:
image: nginx:latest
ports:
- "80:80"
db:
image: postgres:13
environment:
POSTGRES_PASSWORD: example
4.2 Kubernetes 部署文件
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
template:
spec:
containers:
- name: nginx
image: nginx:1.14.2
4.3 GitHub Actions
name: CI Pipeline
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install
- run: npm test
Nodemailer 详细介绍
Nodemailer 是一个 Node.js 模块,用于发送电子邮件。它支持 SMTP、Sendmail、Mailgun、Amazon SES 等多种邮件传输方式,并提供了丰富的功能,如附件、HTML 内容、模板引擎集成等。
1. 核心功能
功能 | 说明 |
---|---|
多传输方式 | SMTP、Sendmail、Mailgun、AWS SES 等 |
HTML 邮件 | 支持富文本邮件(带 CSS 和内联图片) |
附件支持 | 可添加文件、Buffer、Stream 或 URL 作为附件 |
模板引擎 | 支持 EJS、Handlebars、Pug 等 |
安全传输 | 支持 TLS/SSL、OAuth2 认证 |
批量发送 | 可同时发送多封邮件 |
2. 安装
npm install nodemailer
# 或
yarn add nodemailer
3. 基本用法
import nodemailer from "nodemailer";
import yaml from "js-yaml";
import fs from "fs";
import express from "express";
const app = express();
app.use(express.json());
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,
},
});
app.post("/send/mail", async (req, res) => {
const { to, subject, text } = req.body;
transport.sendMail({ to, subject, text, from: mailInfo.user });
res.end("success");
});
app.listen(3000, () => {
console.log("server is running on port 3000");
})
4. 高级功能
4.1 发送附件
const mailOptions = {
// ...其他配置
attachments: [
{
filename: "document.pdf",
path: "./files/document.pdf", // 本地文件
},
{
filename: "image.png",
content: Buffer.from("..."), // Buffer 数据
},
],
};
4.2 使用模板引擎(如 EJS)
const ejs = require("ejs");
const html = ejs.renderFile("./templates/welcome.ejs", { name: "John" });
const mailOptions = {
// ...其他配置
html: html,
};
4.3 OAuth2 认证(Gmail)
const transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
type: "OAuth2",
user: "your-email@gmail.com",
clientId: "your-client-id",
clientSecret: "your-client-secret",
refreshToken: "your-refresh-token",
accessToken: "your-access-token",
},
});
5. 常见问题
5.1 Gmail 报错 Invalid login
- 原因:Google 默认阻止低安全性应用。
- 解决方案:
- 启用 "允许不够安全的应用"(不推荐)。
- 使用 App Password(推荐)。
- 改用 OAuth2(最安全)。
5.2 邮件进入垃圾箱
- 原因:SPF/DKIM/DMARC 未配置。
- 解决方案:
- 使用 企业邮箱(如 Mailgun、SendGrid)。
- 配置 SPF/DKIM 记录。
6. 生产环境建议
场景 | 推荐方案 |
---|---|
小型项目 | SMTP(如 Gmail、Mailgun) |
企业级 | AWS SES、SendGrid |
高并发 | 使用 连接池(pool: true ) |
安全性 | 使用 OAuth2 而非明文密码 |
7. 官方文档
总结
Nodemailer 是 Node.js 生态中最流行的邮件发送库,适用于:
✅ 用户注册验证邮件
✅ 密码重置邮件
✅ 系统通知邮件
✅ 营销邮件(批量发送)
如果你需要在 Node.js 中发送邮件,Nodemailer 是最佳选择! 🚀