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

如何使用Python在Gmail中创建HTML格式的邮件草稿?

解决Gmail通过imaplib创建HTML格式草稿的问题

你之前的代码创建的是纯文本邮件,导致HTML标签被转义显示。要生成带可点击链接的HTML草稿,需要用MIMEText指定HTML类型,而非默认的纯文本格式。以下是修改后的可行代码:

from email.mime.text import MIMEText
import imaplib
import time

# 创建HTML格式邮件
msg = MIMEText('This is the email <a href="https://example.com">body</a>', 'html', 'utf-8')
msg["To"] = "john.doe@gmail.com"
msg["Subject"] = "Subject line"

# (需提前完成IMAP连接与登录)
# imap_ssl = imaplib.IMAP4_SSL('imap.gmail.com')
# imap_ssl.login('your_account@gmail.com', 'your_app_password')

# 将邮件添加到Gmail草稿箱
status, data = imap_ssl.append('"[Google Mail]/Drafts"', "", imaplib.Time2Internaldate(time.time()), msg.as_string().encode('utf-8'))

# 关闭连接
# imap_ssl.close()
# imap_ssl.logout()

核心要点:

  • 使用MIMEText时,第二个参数设为'html',明确告知邮件客户端内容为HTML格式,Gmail会自动解析渲染链接。
  • 邮件内的HTML标签需符合规范,比如链接的href建议填写有效URL(示例中用https://example.com替代了原代码的#)。
  • 确保imap_ssl已完成登录验证,代码中注释了连接、登录及关闭的步骤,需根据自身账号情况补充完整。

内容的提问来源于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:35:00