Python 报错 Could not guess image MIME subtype

发布时间 2023-07-19 11:14:30作者: 南风丶轻语

Python 报错 Could not guess image MIME subtype

问题描述:

使用MIMEImage打包图片时,报错Could not guess image MIME subtype

from email.mime.image import MIMEImage
identification = uuid.uuid4().hex
with open(abspath, "rb") as f:
    content = f.read()
img = MIMEImage(content)
img.add_header("Content-ID", identification)  # 定义图片 ID,在 HTML 文本中引用

报错截图

image-20230719103102357

解决办法

添加一个参数_subtype="xxx"即可xxx就是图片类型,例如png

identification = uuid.uuid4().hex
with open(abspath, "rb") as f:
    content = f.read()
img = MIMEImage(content, _subtype="png")
img.add_header("Content-ID", identification)  # 定义图片 ID,在 HTML 文本中引用

备注

网上说添加_subtype=False也行,但如果你知道图片的类型,直接添加后缀更好,例如我的图片是.png结尾的,我就添加_subtype="png"

源码解析

从源码中可以看到,如果不给_subtype="xxx"参数,则源码会去猜测,猜不到就抛出异常,所以解决办法就是直接告诉它,我是啥格式的图片,不要让它猜

image-20230719103437233