如何使用imaplib将回复邮件以草稿形式追加至邮箱?
问题解决方案
问题分析
你尝试将邮件回复作为草稿追加到邮箱,但imaplib.append()要求传入字节流格式的消息内容,当前代码中MimeMultipart对象调用as_string()返回的是字符串,直接传入会导致适配失败。
修复步骤
核心修改点
imaplib.append()的第四个参数必须是字节类型,只需将as_string()替换为as_bytes(),就能让消息内容符合接口要求。同时建议处理邮件主题编码,避免非ASCII字符乱码。
修改后的完整代码
def answer_email(original, answer_body): for part in original.walk(): if (part.get('Content-Disposition') and part.get('Content-Disposition').startswith("attachment")): part.set_type("text/plain") part.set_payload("Attachment removed: %s (%s, %d bytes)" % (part.get_filename(), part.get_content_type(), len(part.get_payload(decode=True)))) del part["Content-Disposition"] del part["Content-Transfer-Encoding"] new = MIMEMultipart("mixed") body = MIMEMultipart("alternative") body.attach(MIMEText(answer_body, "plain")) body.attach(MIMEText("<html>"+answer_body+"</html>", "html")) new.attach(body) new["Message-ID"] = email.utils.make_msgid() new["In-Reply-To"] = original["Message-ID"] new["References"] = original["Message-ID"] # 处理主题编码,避免非ASCII字符乱码 new["Subject"] = email.header.Header(f"Re: {original['Subject']}", 'utf-8').encode() new["To"] = original["Reply-To"] or original["From"] new["From"] = "me@mysite.com" return new # 关键修改:将消息转为字节流传入append方法 reply_msg = answer_email(msg, respuesta.choices[0].text) imap.append( str(bandeja + '/Gestionados'), '', imaplib.Time2Internaldate(time()), reply_msg.as_bytes() # 替换as_string()为as_bytes() )
额外说明
as_bytes()会直接生成符合MIME标准的字节流,完美适配imaplib.append()的参数要求。- 使用
email.header.Header处理主题字段,能有效避免中文、特殊字符等非ASCII内容出现乱码。 - 确保
To、From等邮件头字段格式符合RFC标准,避免邮件服务器拒绝接收。
内容的提问来源于stack exchange,提问作者hugojm
相关产品推荐
相关产品推荐

