I’d like to create an image using PIL and be able to email it without having to save it to disk.
This is what works, but involves 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’d like to be able to do something like:
import StringIO
tempimg = StringIO.StringIO()
tempimg.write(im.tostring())
img = MIMEImage(tempimage.getvalue(), "JPG")
msg.attach(img)
, which doesn’t work. I’ve found some discussion in Spanish that looks like it addresses the same question, with no solution except a pointer at StringIO.
im.tostringreturns raw image data but you need to pass whole image file data toMIMEImage, so use StringIO module to save the image to memory and use that data: