环境准备
-
安装 OpenClaw

- 从官方仓库下载或使用包管理器安装(如
pip install openclaw)。 - 确保 Python 版本 ≥ 3.8。
- 从官方仓库下载或使用包管理器安装(如
-
配置邮件服务端
- 支持 SMTP(如 Gmail、QQ邮箱、企业邮箱)或 API 方式(如 SendGrid、Amazon SES)。
- 获取 SMTP 服务器地址、端口、加密方式(TLS/SSL)及授权码(非登录密码)。
基本配置
- 创建配置文件(如
config.yaml):smtp: server: "smtp.gmail.com" port: 587 username: "your_email@gmail.com" password: "your_app_password" # 使用应用专用密码 use_tls: true
sender: name: "Your Company" email: "your_email@gmail.com"
logging: level: "INFO" file: "logs/openclaw.log"
2. **初始化 OpenClaw**(Python 脚本):
```python
from openclaw import OpenClaw
claw = OpenClaw(config_path="config.yaml")
claw.connect() # 连接邮件服务器
邮件模板设置
-
创建模板文件(如
templates/welcome.html):<!DOCTYPE html> <html> <body> <h1>欢迎,{{ name }}!</h1> <p>您的验证码是:<strong>{{ code }}</strong></p> <p>有效期 10 分钟。</p> </body> </html> -
加载模板并发送:
from openclaw.template import TemplateEngine
template = TemplateEngine("templates/") html_content = template.render("welcome.html", name="张三", code="123456")
claw.send( to="recipient@example.com", subject="欢迎邮件", html=html_content, attachments=["file.pdf"] # 可选附件 )
---
### **四、自动化发送流程**
1. **批量发送(支持变量替换)**:
```python
recipients = [
{"email": "user1@example.com", "name": "李四", "code": "654321"},
{"email": "user2@example.com", "name": "王五", "code": "987654"},
]
for user in recipients:
html = template.render("welcome.html", name=user["name"], code=user["code"])
claw.send(to=user["email"], subject="您的验证码", html=html)
- 定时发送(结合任务调度):
- 使用 APScheduler 或 Celery 设置定时任务:
from apscheduler.schedulers.blocking import BlockingScheduler
- 使用 APScheduler 或 Celery 设置定时任务:
def send_daily_report(): claw.send(to="team@example.com", subject="日报", html="
今日数据...
")scheduler = BlockingScheduler() scheduler.add_job(send_daily_report, 'cron', hour=18, minute=30) # 每天18:30发送 scheduler.start()
---
### **五、高级功能**
1. **邮件队列**(防止阻塞):
```python
from openclaw.queue import MailQueue
queue = MailQueue(claw, max_workers=5)
queue.add_task(to="user@example.com", subject="队列测试", html="<p>异步发送</p>")
queue.start()
-
跟踪邮件状态:
to="user@example.com", subject="带追踪的邮件", html="<p>内容</p>", callback=lambda status: print(f"发送状态: {status}") ) -
避免被标记为垃圾邮件:
- 配置 SPF/DKIM/DMARC 域名记录。
- 限制发送频率(如每秒 ≤ 5 封)。
- 使用明确的退订链接。
错误处理
try:
claw.send(to="invalid@example", subject="测试", html="<p>内容</p>")
except openclaw.exceptions.SMTPError as e:
print(f"SMTP错误: {e}")
except openclaw.exceptions.TemplateError as e:
print(f"模板错误: {e}")
命令行工具(可选)
# 直接通过命令行发送 openclaw send \ --to "recipient@example.com" \ --subject "测试" \ --template "welcome.html" \ --var name="张三" code="123456" # 批量发送CSV列表 openclaw batch --csv users.csv --template welcome.html
注意事项
-
安全提示:
- 不要将密码硬编码在代码中,使用环境变量或密钥管理服务。
- 建议为发件邮箱开启 两步验证 并使用应用专用密码。
-
性能优化:
- 使用连接池复用 SMTP 连接。
- 对大量收件人使用 BCC(密送) 减少请求次数。
-
合规性:
- 遵守 GDPR/《网络安全法》,提供退订选项。
- 避免在非工作时段发送营销邮件。
通过以上步骤,你可以快速配置 OpenClaw 实现邮件自动发送,如需更详细的功能(如 A/B 测试、点击跟踪),请参考官方文档或集成第三方邮件服务 API。