python - 如何使用python添加嵌入在电子邮件正文中的图像?
问题描述
这是我目前的代码,在 Outlook 中它工作正常,但 GMail 将我的图像显示为附件并且不显示嵌入。我究竟做错了什么?
class RawMailHelper:
def montarRawMail(self, emailSimples):
CHARSET = "utf-8"
msg = MIMEMultipart('mixed')
msg['Subject'] = emailSimples['Message']['Subject']['Data']
msg['From'] = emailSimples['Source']
msg['To'] = ','.join(emailSimples['Destination']['ToAddresses'])
soup = BeautifulSoup(emailSimples['Message']['Body']['Html']['Data'])
i = 1
for img in soup.findAll('img'):
imgInBase64 = img['src'].split(',')[1]
imgData = base64.b64decode(imgInBase64)
imgType = imghdr.what(file=f'image{i}', h=imgData)
att = MIMEImage(imgData)
att.add_header('Content-ID', f'image{i}')
att['Content-Disposition'] = f'inline; filename=image{i}.{imgType}'
msg.attach(att)
img['src'] = f'cid:image{i}'
i += 1
corpoHtml = str(soup)
textpart = MIMEText(emailSimples['Message']['Body']['Text']['Data'], 'plain', CHARSET)
htmlpart = MIMEText(corpoHtml, 'html', CHARSET)
msg_body = MIMEMultipart('alternative')
msg_body.attach(textpart)
msg_body.attach(htmlpart)
msg.attach(msg_body)
解决方案
问题解决了!经过大量研究,我设法找到了解决方案!
att = MIMEImage(imgData)
att.add_header('Content-ID', f'<image{i}.{imgType}>')
att.add_header('X-Attachment-Id', f'image{i}.{imgType}')
att['Content-Disposition'] = f'inline; filename=image{i}.{imgType}'
msg.attach(att)
img['src'] = f'cid:image{i}.{imgType}'
推荐阅读
- c# - 如何在 UWP 中更改特殊字符的颜色
- amazon-web-services - 如何在 Route53 中将多个区域 Load-Balancers Alias 记录设置为单个名称?
- php - PHP在迭代剧集作者对象时将唯一的用户数组添加到新创建的数组
- python - 饼图未在烧瓶应用程序中正确呈现
- node.js - findall include 里面 include by use Sequelize
- sql-server - SQL Server 代理找不到备份作业的证书
- cypress - 赛普拉斯测试 - 用于 URL 匹配
- c++ - 多个类的通用调度程序
- javascript - 如何使用 get 方法从 response.data 中提取道具
- facebook - 无法使用 Facebook Graph API 阻止用户访问页面