Added error checking to the MIMEImage encoding for smtp.py (#5753)

* Added error checking to the MIMEImage encoding for smtp.py

Added fallback to file attachment rather than inline image for images
without a known MIME

* PEP8 reqs to fix previous commit
This commit is contained in:
Jesse Osiecki 2017-02-07 03:43:03 -05:00 committed by Paulus Schoutsen
parent 86da4f511d
commit 9a2c84ee8a

View File

@ -10,6 +10,7 @@ from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText from email.mime.text import MIMEText
from email.mime.image import MIMEImage from email.mime.image import MIMEImage
import email.utils import email.utils
from email.mime.application import MIMEApplication
import voluptuous as vol import voluptuous as vol
@ -179,9 +180,19 @@ def _build_multipart_msg(message, images):
body_text.append('<img src="cid:{}"><br>'.format(cid)) body_text.append('<img src="cid:{}"><br>'.format(cid))
try: try:
with open(atch_name, 'rb') as attachment_file: with open(atch_name, 'rb') as attachment_file:
attachment = MIMEImage(attachment_file.read()) file_bytes = attachment_file.read()
msg.attach(attachment) try:
attachment.add_header('Content-ID', '<{}>'.format(cid)) attachment = MIMEImage(file_bytes)
msg.attach(attachment)
attachment.add_header('Content-ID', '<{}>'.format(cid))
except TypeError:
_LOGGER.warning('Attachment %s has an unkown MIME type.'
' Falling back to file', atch_name)
attachment = MIMEApplication(file_bytes, Name=atch_name)
attachment['Content-Disposition'] = ('attachment; '
'filename="%s"' %
atch_name)
msg.attach(attachment)
except FileNotFoundError: except FileNotFoundError:
_LOGGER.warning('Attachment %s not found. Skipping', _LOGGER.warning('Attachment %s not found. Skipping',
atch_name) atch_name)