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

3.9k Views Asked by At

I am using email.message and smtplib to send emails using python. When an image is sent as an attachment, it raises this error:

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

Here is the code for the image attachment:

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)
1

There are 1 best solutions below

0
On

Rather doing

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

you might do

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

as imghdr.what(file, h=None) does

Tests the image data contained in the file named by file, and returns a string describing the image type. If optional h is provided, the file argument is ignored and h is assumed to contain the byte stream to test.