1

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)
Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33
Coder Station
  • 53
  • 2
  • 8

1 Answers1

0

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.

Daweo
  • 31,313
  • 3
  • 12
  • 25