Convert PIL image to MIMEImage

I would like to create an image using PIL and be able to send it by email without saving it to disk.

This is what works, but includes saving to disk:

from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart msg = MIMEMultipart() im = Image.new("RGB", (200, 200)) with open("tempimg.jpg", "w") as f: im.save(f, "JPEG") with open("tempimg.jpg", 'rb') as f: img = MIMEImage(f.read()) msg.attach(img) 

Now I would like to do something like:

 import StringIO tempimg = StringIO.StringIO() tempimg.write(im.tostring()) img = MIMEImage(tempimage.getvalue(), "JPG") msg.attach(img) 

which does not work. I found some discussion in Spanish , it looks like it solves the same issue without a solution other than a pointer to StringIO.

+4
source share
1 answer

im.tostring returns the raw image data, but you need to transfer the image file data in MIMEImage format, so use the StringIO module to store the image in memory and use this data:

 from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from PIL import Image import cStringIO msg = MIMEMultipart() im = Image.new("RGB", (200, 200)) memf = cStringIO.StringIO() im.save(memf, "JPEG") img = MIMEImage(memf.getvalue()) msg.attach(img) 
+7
source

Source: https://habr.com/ru/post/1386858/


All Articles