I am trying to send an email with images in the body of the email.
I am able to send an email with no images or with images as an attachment but I'm unable to send with the image displayed in the email.
Below is what I have done so far:
from email.encoders import encode_base64
from email.mime.base import MIMEBase
from PIL import Image
from io import BytesIO
from smtplib import SMTPException
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
import smtplib
msg = MIMEMultipart("related")
msg['Subject'] = subject #time
msg['From'] = from_addr
msg['To'] = to_addr
html_output = "your html here"
msg.attach(MIMEText(html_output, "html"))
#plots is a dictionary of images
for image_name, image_location in plots.items():
img = Image.open(BytesIO(image_location))
msg.attach(img)
smtplib.SMTP(host).sendmail(from_addr, to_addr, msg.as_string())
I get an error saying the below in Databricks
/usr/lib/python3.8/email/generator.py in _handle_multipart(self, msg)
274 s = self._new_buffer()
275 g = self.clone(s)
--> 276 g.flatten(part, unixfrom=False, linesep=self._NL)
277 msgtexts.append(s.getvalue())
278 # BAW: What about boundaries that are wrapped in double-quotes?
/usr/lib/python3.8/email/generator.py in flatten(self, msg, unixfrom, linesep)
105 # they are processed by this code.
106 old_gen_policy = self.policy
--> 107 old_msg_policy = msg.policy
108 try:
109 self.policy = policy
/databricks/python/lib/python3.8/site-packages/PIL/Image.py in __getattr__(self, name)
539 )
540 return self._category
--> 541 raise AttributeError(name)
542
543 @property
AttributeError: policy
What am I doing incorrectly?