1

I created a script for mailing images to my parents. But while attaching files, I'm getting a Traceback for a KeyError, following attached is the source code

import smtplib
import os
import imghdr
from email.message import EmailMessage 

username = os.environ.get('EMAIL_USER')
password = os.environ.get('EMAIL_PASS')

boy = EmailMessage()
boy['Subject'] = 'Check this pussy'
boy['From'] = username
boy['To'] = 'kryptonite@pm.me'
boy.set_content('image attached')

with open('pussy.jpg', 'rb') as f:
    file_data = f.read
    file_type = imghdr.what(f.name)
    file_name = f.name
    # print(file_type)

boy.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as app:
    app.login(username, password)
    app.send_message(boy)

For this code I'm getting the following traceback

[Running] python -u "s:\DEV_ENV\python_playground\email_test.py"
Traceback (most recent call last):
  File "s:\DEV_ENV\python_playground\email_test.py", line 32, in <module>
    boy.add_attachment(file_data)
  File "C:\Program Files\Python37\lib\email\message.py", line 1156, in add_attachment
    self._add_multipart('mixed', *args, _disp='attachment', **kw)
  File "C:\Program Files\Python37\lib\email\message.py", line 1144, in _add_multipart
    part.set_content(*args, **kw)
  File "C:\Program Files\Python37\lib\email\message.py", line 1171, in set_content
    super().set_content(*args, **kw)
  File "C:\Program Files\Python37\lib\email\message.py", line 1101, in set_content
    content_manager.set_content(self, *args, **kw)
  File "C:\Program Files\Python37\lib\email\contentmanager.py", line 35, in set_content
    handler = self._find_set_handler(msg, obj)
  File "C:\Program Files\Python37\lib\email\contentmanager.py", line 58, in _find_set_handler
    raise KeyError(full_path_for_error)
KeyError: 'builtins.builtin_function_or_method'

[Done] exited with code=1 in 0.159 seconds

Is there anything wrong with the code?

Frank Yucheng Gu
  • 1,807
  • 7
  • 21

2 Answers2

0

It turns out this might be an error with the imghdr library. See link imghdr / python - Can't detec type of some images (image extension). The .what method only works 80% of the time, according to the poster. Monkeypatch included in this answer in the same question: https://stackoverflow.com/a/57693121/5660315.

VirtualScooter
  • 1,792
  • 3
  • 18
  • 28
0

While reading an image file, you missed the parenthesis at f.read. Corrected line would be

file_data = f.read()

Code will run successfully once corrected.

toyota Supra
  • 3,181
  • 4
  • 15
  • 19