OpenClaw-AI助手入门教程-配置邮件通知
说明:
- 当任务完成使用指定的邮箱通知
- 实现方式:使用openclaw的开发能力来编程生成一个自己使用的python脚本即可
步骤1-获取qq邮箱授权码:
登录邮箱并进入设置:在电脑浏览器里打开QQ邮箱官网 (mail.qq.com),登录后,点击页面顶部的 “设置” 链接,然后选择 “帐户” 选项卡。
找到并开启服务:在“帐户”页面往下拉,找到 “POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务” 这一栏。点击任一服务(比如 “IMAP/SMTP服务”)右侧的 “开启” 按钮。
完成安全验证:这时会弹出一个窗口,要求你验证身份。根据提示,用你绑定该邮箱的手机号发送一条指定短信到指定号码。发送完成后,在电脑上点击 “我已发送” 或类似的确认按钮。
获取并保存授权码:验证通过后,系统就会弹出一串16位的授权码。请务必马上复制并把它保存好(比如记在备忘录里或截图保存),因为这个弹窗关掉后就再也看不到了。如果在第三方客户端设置时还需要,只能重新生成
步骤2-生成发送邮件脚本和配置:
- 确认邮箱和授权码后,使用openclaw的开发能力来编程生成一个自己使用的python脚本:
- 使用web-ui的chat窗口,输入如下的参考python脚本,邮箱和授权码:
#!/usr/bin/env python3
"""
OpenClaw邮件发送系统
支持环境变量配置,敏感信息存储在.env文件中
"""
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import argparse
import os
import sys
from pathlib import Path
def load_env():
"""加载环境变量"""
env_path = Path(__file__).parent / '.env'
# 如果.env文件存在,读取它
if env_path.exists():
with open(env_path, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
key, value = line.split('=', 1)
os.environ[key.strip()] = value.strip()
# 返回配置字典
config = {
'qq_email': os.getenv('QQ_EMAIL', ''),
'qq_password': os.getenv('QQ_EMAIL_PASSWORD', ''),
'smtp_server': os.getenv('SMTP_SERVER', 'smtp.qq.com'),
'smtp_port': int(os.getenv('SMTP_PORT', '587')),
'default_recipient': os.getenv('DEFAULT_RECIPIENT', ''),
'use_tls': os.getenv('USE_TLS', 'true').lower() == 'true',
'use_ssl': os.getenv('USE_SSL', 'false').lower() == 'true',
}
return config
def send_email(to_email, subject, body, from_email=None, password=None, config=None):
"""
通过QQ邮箱SMTP发送邮件
Args:
to_email: 收件人邮箱
subject: 邮件主题
body: 邮件内容
from_email: 发件人邮箱(可选)
password: QQ邮箱授权码(可选)
config: 配置字典(可选)
Returns:
bool: 发送是否成功
"""
if config is None:
config = load_env()
# 使用配置中的值
smtp_server = config['smtp_server']
smtp_port = config['smtp_port']
use_tls = config['use_tls']
use_ssl = config['use_ssl']
# 如果没有提供发件人邮箱,使用配置中的值
if not from_email:
from_email = config['qq_email']
# 如果没有提供密码,使用配置中的值
if not password:
password = config['qq_password']
# 验证配置
if not from_email:
print("错误:未设置发件人邮箱")
print(" 请在.env文件中设置QQ_EMAIL环境变量")
return False
if not password:
print("错误:未设置QQ邮箱授权码")
print(" 请在.env文件中设置QQ_EMAIL_PASSWORD环境变量")
return False
# 创建邮件
message = MIMEMultipart("alternative")
message["Subject"] = subject
message["From"] = from_email
message["To"] = to_email
# 添加纯文本和HTML版本
text_part = MIMEText(body, "plain", "utf-8")
html_part = MIMEText(f"""
<html>
<head>
<meta charset="utf-8">
<style>
body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
.container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
.header {{ background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin-bottom: 20px; }}
.content {{ background-color: white; padding: 20px; border: 1px solid #dee2e6; border-radius: 5px; }}
.footer {{ margin-top: 20px; padding-top: 15px; border-top: 1px solid #dee2e6; color: #6c757d; font-size: 12px; }}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h2>{subject}</h2>
</div>
<div class="content">
<pre style="white-space: pre-wrap; font-family: inherit;">{body}</pre>
</div>
<div class="footer">
<p>此邮件由OpenClaw邮件系统自动发送</p>
<p>发送时间: {os.environ.get('SEND_TIME', '')}</p>
</div>
</div>
</body>
</html>
""", "html", "utf-8")
message.attach(text_part)
message.attach(html_part)
try:
# 设置发送时间环境变量(用于HTML模板)
os.environ['SEND_TIME'] = os.popen('date').read().strip()
print(f"正在发送邮件...")
print(f" SMTP服务器: {smtp_server}:{smtp_port}")
print(f" 发件人: {from_email}")
print(f" 收件人: {to_email}")
print(f" 主题: {subject}")
# 创建安全连接
context = ssl.create_default_context()
if use_ssl:
# SSL连接
with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
server.login(from_email, password)
server.sendmail(from_email, to_email, message.as_string())
elif use_tls:
# TLS连接
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls(context=context) # 启用TLS加密
server.login(from_email, password)
server.sendmail(from_email, to_email, message.as_string())
else:
# 非加密连接(不推荐)
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.login(from_email, password)
server.sendmail(from_email, to_email, message.as_string())
print(f"邮件发送成功!")
return True
except smtplib.SMTPAuthenticationError as e:
print(f"认证失败: {e}")
print(" 请检查QQ邮箱和授权码是否正确")
print(" 注意:需要使用授权码而非登录密码")
return False
except Exception as e:
print(f"邮件发送失败: {e}")
return False
def main():
parser = argparse.ArgumentParser(
description="OpenClaw邮件发送系统",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
示例:
%(prog)s --to recipient@example.com --subject "测试" --body "内容"
%(prog)s --to default --subject "提醒" --body "记得开会" # 使用默认收件人
环境变量配置:
请创建.env文件并设置以下变量:
QQ_EMAIL=your_email@qq.com
QQ_EMAIL_PASSWORD=your_authorization_code
DEFAULT_RECIPIENT=default_recipient@qq.com
"""
)
parser.add_argument("--to", required=True, help="收件人邮箱(或使用'default'使用默认收件人)")
parser.add_argument("--subject", required=True, help="邮件主题")
parser.add_argument("--body", required=True, help="邮件内容")
parser.add_argument("--from", dest="from_email", help="发件人邮箱(默认使用QQ_EMAIL环境变量)")
parser.add_argument("--password", help="QQ邮箱授权码(默认使用QQ_EMAIL_PASSWORD环境变量)")
parser.add_argument("--config", help="配置文件路径(默认使用当前目录下的.env文件)")
args = parser.parse_args()
# 加载配置
config = load_env()
# 处理收件人
to_email = args.to
if to_email.lower() == 'default':
to_email = config['default_recipient']
if not to_email:
print("错误:未设置默认收件人")
print("请在.env文件中设置DEFAULT_RECIPIENT环境变量")
sys.exit(1)
print(f"使用默认收件人: {to_email}")
success = send_email(
to_email=to_email,
subject=args.subject,
body=args.body,
from_email=args.from_email,
password=args.password,
config=config
)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()
- openclaw应该会自动根据这个参考脚本,邮箱和授权码,自动帮你配置好这个邮箱并给出测试报告
- 还可以配置一个定时提醒,比如在web-ui的chat窗口,发指令:增加每日9点的起床提醒推送的邮箱
总结:
- openclaw的自动化的确是目前看到最好的,能自动完成很多任务,后面再继续探索。
获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号


















