读取/发送QQ邮件,支持IMAP读取、SMTP发送和多编码解析。触发场景:查看、读取、筛选邮件或发送邮件。
QQ邮箱读取和发送是一项面向实际任务的技能,主要用于通过 IMAP 协议读取 QQ 邮箱邮件;用户提到以下场景时使用:;
"查看当天邮件";"搜索邮件";"有新的邮件吗";需要提前配置QQ 邮箱 IMAP:;在 QQ 邮箱设置中开启 IMAP 服务;创建授权码(不是登录密码);配置 secrets 文件: ~/.openclaw/secrets/mail_qq.env;安全注意事项。
它将相关步骤、工具调用和结果整理方式集中到统一流程中,帮助使用者更快完成目标并减少重复操作。从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。该技能适合用于一次性任务,也可以接入自动化工作流,与其他技能或上层代理配合完成更完整的业务链路;在组合使用时,应明确每一步的输入输出关系,并避免不同步骤之间出现参数冲突。
通过 IMAP 协议读取 QQ 邮箱邮件
用户提到以下场景时使用:
需要提前配置QQ 邮箱 IMAP:
~/.openclaw/secrets/mail_qq.envMAIL_USER=your_email@qq.com MAIL_PASS=your_auth_code
600(仅所有者可读),防止其他用户读取敏感信息~/.openclaw/secrets/ 目录默认已经加入.gitignore,不会被提交到版本控制import imaplib
import email
from email.header import decode_header
IMAP_HOST = 'imap.qq.com'
IMAP_PORT = 993
def connect_mail(user, password):
mail = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT)
mail.login(user, password)
mail.select('INBOX')
return mail
# 搜索最近7天的邮件
week_ago = (datetime.now() - timedelta(days=7)).strftime('%d-%b-%Y')
typ, msg_ids = mail.search(None, f'SINCE {week_ago}')
def decode_header_value(header_value):
"""兼容多种编码的解码"""
if not header_value:
return ""
decoded_parts = []
for content, encoding in decode_header(header_value):
if isinstance(content, bytes):
try:
decoded = content.decode(encoding if encoding else 'utf-8')
except:
# 尝试其他常见编码
for enc in ['gbk', 'gb2312', 'utf-8', 'big5', 'latin1']:
try:
decoded = content.decode(enc)
break
except:
decoded = content.decode('utf-8', errors='ignore')
else:
decoded = str(content)
decoded_parts.append(decoded)
return ''.join(decoded_parts)
邮件正文可能包含 HTML,需要清理:
import re
def get_text_body(msg):
body = ''
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() == 'text/html':
payload = part.get_payload(decode=True)
encoding = part.get_content_charset() or 'utf-8'
body = payload.decode(encoding, errors='ignore')
break
else:
payload = msg.get_payload(decode=True)
encoding = msg.get_content_charset() or 'utf-8'
body = payload.decode(encoding, errors='ignore')
# 清理HTML标签
text = re.sub(r'<[^>]+>', ' ', body)
text = text.replace(' ', ' ')
text = text.replace('&', '&')
text = re.sub(r's+', ' ', text)
return text
根据用户需求过滤邮件,常见关键词类型:
通过 QQ 邮箱 SMTP 服务发送邮件,使用相同的授权码进行认证
发送邮件使用与读取邮件相同的凭据文件 ~/.openclaw/secrets/mail_qq.env
MAIL_USER=your_email@qq.com MAIL_PASS=your_auth_code
smtp.qq.com新建 qq_mail_sender.py 模块提供了发送邮件的功能
from qq_mail_sender import send_email
send_email(
to="recipient@example.com",
subject="测试邮件主题",
body="这是一封测试邮件正文"
)
python qq_mail_sender.py recipient@example.com "测试邮件主题" "这是一封测试邮件正文"
import smtplib
import ssl
from email.message import EmailMessage
from email.header import Header
import os
def load_credentials(env_path=r"C:UsersAdministrator.openclawsecretsmail_qq.env"):
"""从env文件加载MAIL_USER和MAIL_PASS"""
creds = {}
if os.path.exists(env_path):
with open(env_path, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
if '=' in line:
k, v = line.split('=', 1)
creds[k.strip()] = v.strip()
return creds
def build_message(sender, to, subject, body, cc=None, bcc=None):
"""构建带有适当编码的EmailMessage"""
msg = EmailMessage()
msg['From'] = sender
msg['To'] = to
if cc:
msg['Cc'] = cc
if bcc:
msg['Bcc'] = bcc
msg['Subject'] = Header(subject, 'utf-8')
msg.set_content(body, charset='utf-8')
return msg
def send_email(to, subject, body, cc=None, bcc=None):
"""
通过QQ SMTP发送邮件
使用SSL连接端口465
"""
creds = load_credentials()
user = creds.get('MAIL_USER')
password = creds.get('MAIL_PASS')
if not user or not password:
raise ValueError("凭据文件中缺少MAIL_USER或MAIL_PASS")
msg = build_message(user, to, subject, body, cc, bcc)
context = ssl.create_default_context()
with smtplib.SMTP_SSL('smtp.qq.com', 465, context=context) as server:
server.login(user, password)
server.send_message(msg)
print(f"邮件已发送至 {to}")
600(仅所有者可读),防止其他用户读取敏感信息~/.openclaw/secrets/ 目录默认已经加入.gitignore,不会被提交到版本控制详细的发送邮件参考请参见:references/message-sending.md
相关专题
热门下载
相关下载
精品课程
共6课时 | 54.7万人学习
共89课时 | 134.1万人学习
共49课时 | 82.6万人学习
最新文章