首页 > 解决方案 > AttributeError:“字节”对象没有属性“告诉”

问题描述

我正在使用email.messagesmtplib使用 python 发送电子邮件。当图像作为附件发送时,会引发以下错误:

AttributeError: 'bytes' object has no attribute 'tell'

这是图像附件的代码:

if filetype.lower() in ['jpg','jpeg','png','gif']:
    with open(filename, 'rb') as file:
        file_data = file.read()
        image_type = imghdr.what(file_data)
    
    actual_filename = filename.split('/')[-1]
    msg.add_attachment(file_data, maintype='image', subtype=image_type, filename=actual_filename)

标签: pythonimagesmtplibimghdr

解决方案


宁愿做

with open(filename, 'rb') as file:
    file_data = file.read()
    image_type = imghdr.what(file_data)

你可能会

image_type = imghdr.what(filename)
with open(filename, 'rb') as file:
    file_data = file.read()

一样imghdr.what(file, h=None)_

测试 file 命名的文件中包含的图像数据,并返回描述图像类型的字符串。如果提供了可选的 h,则忽略 file 参数并假定 h 包含要测试的字节流。


推荐阅读