Python调用Mailgun发送内嵌图片邮件的编码错误与图片不显示问题咨询
问题1:UnicodeDecodeError: 'cp932' 编码错误解决方案
错误原因:你在打开ChartImage图片文件时使用了默认文本模式,Windows系统默认使用cp932编码解码文件内容,而图片是二进制文件,解码自然失败。
解决方法:将open(ChartImage)修改为open(ChartImage, 'rb'),指定二进制读取模式,跳过编码解码逻辑即可。
修正后的对应代码段:
files=[("inline", (ChartImage, open(ChartImage, "rb").read())), ("attachment", (FileAttachment, open(FileAttachment,"rb").read()))],
问题2:邮件正文内嵌图片无法显示解决方案
错误原因:
- 你直接将本地图片路径写在html的img标签src属性中,收件人邮箱无法访问你本地设备的文件
- 没有将图片作为inline类型附件提交给Mailgun,也没有使用cid规则引用内嵌资源
解决步骤:
- 在files参数中添加inline类型的图片配置,指定图片文件名和MIME类型
- 将html中img的src属性修改为
cid:对应图片文件名,文件名需和你inline配置中的文件名完全一致
修正后的完整函数代码:
# function to send email out def Heroku_Mailgun_Send_Email(Email_to, Email_subject, Email_body, FileAttachment, ChartImage, Email_API_key, Email_domain): return requests.post( f"https://api.mailgun.net/v3/{Email_domain}/messages", auth=("api", Email_API_key), files=[("attachment", (FileAttachment, open(FileAttachment,'rb').read())), # 添加inline图片配置,指定MIME类型为image/png ("inline", (ChartImage, open(ChartImage, 'rb').read(), "image/png"))], data={ "from": f"NG Ying Jian <mailgun@{Email_domain}>", "to": Email_to, "subject": Email_subject, "text": Email_body, # src修改为cid:加图片文件名 "html": f"<html> \ <head> \ <title>HTML img Tag</title> \ </head> \ <body> \ <img src=\"cid:{ChartImage}\" width='1000' height='500'> \ </body> \ </html>", })
小提示:如果需要更稳妥的资源管理,可以用with语句打开文件,避免文件句柄泄漏。
内容的提问来源于stack exchange,提问作者yjng
相关产品推荐
相关产品推荐

