跳到主要内容

AWS SES 邮件发送器

Github StackBlitz

这是一个基于 AWS SES 的 Golang 电子邮件发送服务,它仅提取了 我的开源项目 中的基础发送功能。

特性

  • 使用 AWS SES 发送电子邮件
  • 设计时考虑了每日发送限制和每秒发送速率
  • 定时发送和消息分组
  • 电子邮件打开跟踪和结果收集
  • 按消息组查看每日发送计数和投递结果

流程图

要求

基本要求

  • Go 1.22 或更高版本
  • AWS 账户和配置
    • AWS SES 服务已激活
    • 发件人邮箱或域名验证完成
    • 拥有 SES 权限的 IAM 用户
    • AWS Access Key 和 Secret Key
  • PostgreSQL 14.0 或更高版本
  • (可选) Docker

AWS SES 配置

  1. 在 AWS SES 控制台验证发件人邮箱/域名
  2. 请求移除 SES 沙盒模式 (用于生产环境)
  3. 创建 SNS 主题并设置 SES 反馈通知
  4. 授予 IAM 用户以下权限
  • ses:SendEmail
  • ses:SendRawEmail
  • sns:Publish (如果使用 SNS 进行投递通知)
  • sns:Subscribe (如果使用 SNS 进行投递通知)

项目结构

aws-ses-sender/
├── main.go # Application entry point
├── api/ # HTTP API related code
│ ├── handler.go # API handler functions
│ ├── route.go # API routing configuration
│ ├── server.go # HTTP server setup/execution
│ └── middlewares.go # API authentication middleware
├── cmd/ # Background job code
│ ├── scheduler.go # Pending email scheduler
│ └── sender.go # SES email sending processor
├── config/ # Application settings
│ ├── env.go # Environment variable management
│ └── db.go # Database connection settings
├── model/ # Database models
│ └── email.go # GORM model definitions
└── pkg/aws/ # AWS service integration
└── ses.go # SES email sending

设置

先决条件

  • Go 语言开发环境
  • AWS 账户和 SES 服务配置
    • 发件人邮箱/域名验证
    • 创建拥有 SES 权限的 IAM 用户
  • PostgreSQL 数据库
  • (可选) Sentry DSN

配置

在项目根目录创建 .env 文件并设置以下环境变量

# AWS Related
AWS_ACCESS_KEY_ID=your_access_key
AWS_SECRET_ACCESS_KEY=your_secret_key
AWS_REGION=ap-northeast-2
EMAIL_SENDER=sender@example.com

# Server and API
SERVER_PORT=3000
API_KEY=your_api_key
SERVER_HOST=http://localhost:3000

# Database (PostgreSQL)
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=postgres
DB_NAME=postgres

# Sending rate per second
EMAIL_RATE=14

# Sentry (Optional)
SENTRY_DSN=your_sentry_dsn

安装和执行

  1. 克隆仓库

    git clone <repository_URL>
    cd aws-ses-sender
  2. 安装依赖

    go mod tidy
  3. 运行应用

    go run main.go

API 端点

电子邮件发送请求

POST /v1/messages

请求体示例

{
"messages": [
{
"topicId": "promotion-event-2024",
"emails": ["recipient1@example.com", "recipient2@example.com"],
"subject": "Special Promotion Notice",
"content": "<h1>Hello!</h1><p>Check out our special promotion details.</p>",
"scheduledAt": "2024-12-25T10:00:00+09:00"
}
]
}

查看主题发送统计

GET /v1/topics/:topicId

电子邮件打开跟踪

GET /v1/events/open?requestId={requestId}

查看发送统计

GET /v1/events/counts/sent?hours={hours}

接收发送结果 (AWS SNS)

POST /v1/events/results