You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python创建Gmail邮件草稿遇IMAP文件夹及命令解析错误求助

解决Gmail IMAP添加草稿失败的问题

问题原因分析

你遇到的两个错误分别由以下原因导致:

  1. 初始的[Gmail]/Drafts路径不匹配你的邮箱实际文件夹名称,通过list()查到实际是[Google Mail]/Drafts
  2. 修改路径后出现的BAD错误,是因为文件夹名称包含空格未正确引用,加上邮件格式存在语法错误和生成方式不符合IMAP要求

分步解决方案

1. 正确处理文件夹路径

由于[Google Mail]/Drafts包含空格,IMAP命令中需要对该名称进行引号包裹。可以直接使用imaplib的内置方法自动处理,或者手动用双引号包裹路径:

# 方式1:自动引用(推荐)
folder = imaplib.imaplib._Authenticator.mailbox_quote("[Google Mail]/Drafts")
# 方式2:手动包裹双引号
folder = '"[Google Mail]/Drafts"'

2. 修复邮件格式问题

你的代码存在两处邮件格式错误:

  • To字段缺少闭合的>,语法无效
  • 直接用str(message).encode("utf-8")生成的邮件内容不符合RFC 2822标准,Gmail无法解析

改用email.generator.BytesGenerator生成正确的字节流邮件:

3. 完整修正代码

from email.message import Message
from email.generator import BytesGenerator
import imaplib
import time
import io

with imaplib.IMAP4_SSL(host="imap.gmail.com", port=imaplib.IMAP4_SSL_PORT) as imap_ssl:
    print("Logging into mailbox...")
    # 注意:使用Gmail应用专用密码(开启两步验证时必须用这个,不能用普通密码)
    resp_code, response = imap_ssl.login('name@gmail.com', 'your_app_password')

    # 创建格式正确的邮件
    message = Message()
    message["From"] = "You <me@example.com>"
    # 修复To字段的闭合括号
    message["To"] = "recipient <someone@example.com>"
    message["Subject"] = "This is a subject"
    message.set_payload("This is the email body")

    # 生成符合RFC 2822标准的字节流邮件
    msg_bytes = io.BytesIO()
    generator = BytesGenerator(msg_bytes, mangle_from_=False)
    generator.flatten(message)
    utf8_message = msg_bytes.getvalue()

    # 正确引用文件夹路径
    folder = imaplib.imaplib._Authenticator.mailbox_quote("[Google Mail]/Drafts")
    # 执行APPEND命令,添加\\Draft标记确保邮件被识别为草稿
    status, data = imap_ssl.append(folder, '\\Draft', imaplib.Time2Internaldate(time.time()), utf8_message)
    print(f"Status: {status}, Response: {data}")

额外注意事项

  • 确保开启Gmail的IMAP功能:在Gmail设置的「转发和POP/IMAP」选项中启用IMAP访问
  • 应用专用密码获取:账号开启两步验证后,在Google账号安全设置中生成应用专用密码,用于IMAP登录

内容的提问来源于stack exchange,提问作者Sebastian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 08:25:06