{"skill":{"slug":"qq-mail-read-send","displayName":"qq-mail-read-send","summary":"读取和发送QQ邮箱邮件。使用IMAP协议读取，SMTP协议发送。支持多种编码解析。触发场景：用户要求查看邮箱、读取邮件、查看最近邮件、筛选特定邮件、发送邮件等","description":"---\nname: qq-mail-read-send\ndescription: 读取和发送QQ邮箱邮件。使用IMAP协议读取，SMTP协议发送。支持多种编码解析。触发场景：用户要求查看邮箱、读取邮件、查看最近邮件、筛选特定邮件、发送邮件等\nhomepage: https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256\nmetadata:\n  {\n    \"openclaw\": {\n      \"emoji\": \"📧\",\n      \"requires\": {\n        \"env\": [\"MAIL_USER\", \"MAIL_PASS\"],\n        \"config\": [\"~/.openclaw/secrets/mail_qq.env\"]\n      },\n      \"install\": []\n    }\n  }\n---\n\n# QQ邮箱读取和发送\n通过 IMAP 协议读取 QQ 邮箱邮件\n## 触发条件\n\n用户提到以下场景时使用：\n- \"查看邮箱\"\n- \"读取邮件\"\n- \"查看最近邮件\"\n- \"查看当天邮件\"\n- \"搜索邮件\"\n- \"有新的邮件吗\"\n\n## 配置\n\n需要提前配置QQ 邮箱 IMAP：\n1. 在 QQ 邮箱设置中开启 IMAP 服务\n2. 创建授权码（不是登录密码）\n3. 配置 secrets 文件：`~/.openclaw/secrets/mail_qq.env`\n   ```\n   MAIL_USER=your_email@qq.com\n   MAIL_PASS=your_auth_code\n   ```\n\n### 安全注意事项\n- 凭据文件必须设置权限为 `600`（仅所有者可读），防止其他用户读取敏感信息\n- `~/.openclaw/secrets/` 目录默认已经加入.gitignore，不会被提交到版本控制\n- 不要将授权码提交到代码仓库或分享给他人\n## 使用方法\n\n### 1. 连接邮箱\n\n```python\nimport imaplib\nimport email\nfrom email.header import decode_header\n\nIMAP_HOST = 'imap.qq.com'\nIMAP_PORT = 993\n\ndef connect_mail(user, password):\n    mail = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT)\n    mail.login(user, password)\n    mail.select('INBOX')\n    return mail\n```\n\n### 2. 搜索邮件\n\n```python\n# 搜索最近7天的邮件\nweek_ago = (datetime.now() - timedelta(days=7)).strftime('%d-%b-%Y')\ntyp, msg_ids = mail.search(None, f'SINCE {week_ago}')\n```\n\n### 3. 解析邮件\n\n```python\ndef decode_header_value(header_value):\n    \"\"\"兼容多种编码的解码\"\"\"\n    if not header_value:\n        return \"\"\n    decoded_parts = []\n    for content, encoding in decode_header(header_value):\n        if isinstance(content, bytes):\n            try:\n                decoded = content.decode(encoding if encoding else 'utf-8')\n            except:\n                # 尝试其他常见编码\n                for enc in ['gbk', 'gb2312', 'utf-8', 'big5', 'latin1']:\n                    try:\n                        decoded = content.decode(enc)\n                        break\n                    except:\n                        decoded = content.decode('utf-8', errors='ignore')\n        else:\n            decoded = str(content)\n        decoded_parts.append(decoded)\n    return ''.join(decoded_parts)\n```\n\n### 4. 提取正文\n\n邮件正文可能包含 HTML，需要清理：\n\n```python\nimport re\n\ndef get_text_body(msg):\n    body = ''\n    if msg.is_multipart():\n        for part in msg.walk():\n            if part.get_content_type() == 'text/html':\n                payload = part.get_payload(decode=True)\n                encoding = part.get_content_charset() or 'utf-8'\n                body = payload.decode(encoding, errors='ignore')\n                break\n    else:\n        payload = msg.get_payload(decode=True)\n        encoding = msg.get_content_charset() or 'utf-8'\n        body = payload.decode(encoding, errors='ignore')\n    \n    # 清理HTML标签\n    text = re.sub(r'<[^>]+>', ' ', body)\n    text = text.replace('&nbsp;', ' ')\n    text = text.replace('&amp;', '&')\n    text = re.sub(r'\\s+', ' ', text)\n    return text\n```\n\n## 邮件过滤\n\n根据用户需求过滤邮件，常见关键词类型：\n- 通知类：通知、提醒、公告\n- 业务类：订单、发货、支付\n- 职位类：面试、邀请、邀约（仅当用户明确需要时）\n## 注意事项\n\n1. QQ 邮箱必须使用授权码登录，非登录密码\n2. 邮件编码可能为GBK/GB2312/UTF-8 等，需要多种编码尝试\n3. IMAP 搜索不支持中文，使用 SINCE 获取所有邮件后本地过滤\n\n## 发送邮件\n通过 QQ 邮箱 SMTP 服务发送邮件，使用相同的授权码进行认证\n### 配置\n发送邮件使用与读取邮件相同的凭据文件 `~/.openclaw/secrets/mail_qq.env`\n```\nMAIL_USER=your_email@qq.com\nMAIL_PASS=your_auth_code\n```\n\n### SMTP 设置\n- 主机为 `smtp.qq.com`\n- 端口为 465 (SSL) 或 587 (STARTTLS)\n- 授权码： 与 IMAP 相同的授权码（非登录密码）\n### 使用方法\n\n#### 1. 使用 Python 模块发送邮件\n新建 `qq_mail_sender.py` 模块提供了发送邮件的功能\n```python\nfrom qq_mail_sender import send_email\n\nsend_email(\n    to=\"recipient@example.com\",\n    subject=\"测试邮件主题\",\n    body=\"这是一封测试邮件正文\"\n)\n```\n\n#### 2. 命令行方式\n```bash\npython qq_mail_sender.py recipient@example.com \"测试邮件主题\" \"这是一封测试邮件正文\"\n```\n\n#### 3. 详细代码示例（在 qq_mail_sender.py 中）\n\n```python\nimport smtplib\nimport ssl\nfrom email.message import EmailMessage\nfrom email.header import Header\nimport os\n\ndef load_credentials(env_path=r\"C:\\Users\\Administrator\\.openclaw\\secrets\\mail_qq.env\"):\n    \"\"\"从env文件加载MAIL_USER和MAIL_PASS\"\"\"\n    creds = {}\n    if os.path.exists(env_path):\n        with open(env_path, 'r') as f:\n            for line in f:\n                line = line.strip()\n                if line and not line.startswith('#'):\n                    if '=' in line:\n                        k, v = line.split('=', 1)\n                        creds[k.strip()] = v.strip()\n    return creds\n\ndef build_message(sender, to, subject, body, cc=None, bcc=None):\n    \"\"\"构建带有适当编码的EmailMessage\"\"\"\n    msg = EmailMessage()\n    msg['From'] = sender\n    msg['To'] = to\n    if cc:\n        msg['Cc'] = cc\n    if bcc:\n        msg['Bcc'] = bcc\n    msg['Subject'] = Header(subject, 'utf-8')\n    msg.set_content(body, charset='utf-8')\n    return msg\n\ndef send_email(to, subject, body, cc=None, bcc=None):\n    \"\"\"\n    通过QQ SMTP发送邮件\n    使用SSL连接端口465\n    \"\"\"\n    creds = load_credentials()\n    user = creds.get('MAIL_USER')\n    password = creds.get('MAIL_PASS')\n    if not user or not password:\n        raise ValueError(\"凭据文件中缺少MAIL_USER或MAIL_PASS\")\n\n    msg = build_message(user, to, subject, body, cc, bcc)\n\n    context = ssl.create_default_context()\n    with smtplib.SMTP_SSL('smtp.qq.com', 465, context=context) as server:\n        server.login(user, password)\n        server.send_message(msg)\n    print(f\"邮件已发送至 {to}\")\n```\n\n### 安全注意事项\n- 凭据文件必须设置权限为 `600`（仅所有者可读），防止其他用户读取敏感信息\n- `~/.openclaw/secrets/` 目录默认已经加入.gitignore，不会被提交到版本控制\n- 不要将授权码提交到代码仓库或分享给他人\n- 建议先用少量收件人进行测试\n### 参考文档\n详细的发送邮件参考请参见：`references/message-sending.md`","tags":{"latest":"1.0.1"},"stats":{"comments":0,"downloads":418,"installsAllTime":0,"installsCurrent":0,"stars":1,"versions":2},"createdAt":1777822260221,"updatedAt":1778492838254},"latestVersion":{"version":"1.0.1","createdAt":1777822619500,"changelog":"- 修正了文档中的编码异常和乱码问题，统一描述与参数命名\n- 明确了配置、权限设置和安全建议的表述\n- 修复并补全部分邮件场景和过滤说明\n- 对示例代码和命令行使用说明进行了规范化完善\n- 移除乱码字符，提升文档可读性","license":"MIT-0"},"metadata":{"setup":[{"key":"MAIL_USER","required":true},{"key":"MAIL_PASS","required":true},{"key":"~/.openclaw/secrets/mail_qq.env","required":true}],"os":null,"systems":null},"owner":{"handle":"openclawzhangchong","userId":"s178cqx9kma3mpnvqe8evteyr983hvb4","displayName":"张翀","image":"https://avatars.githubusercontent.com/u/270544860?v=4"},"moderation":{"isSuspicious":false,"isMalwareBlocked":false,"verdict":"clean","reasonCodes":["review.llm_review"],"summary":"Review: review.llm_review","engineVersion":"v2.4.24","updatedAt":1780090736034}}