I have an image in memory that I've created (using numpy and PIL), and I'd like to attach it to a created email programatically. I know I could save it to the filesystem, and then reload/attach it, but it seems in-efficient: is there a way to just pipe it to the mime attachment without saving?
The save/reload version:
from PIL import Image
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
...some img creation steps...
msg = MIMEMultipart()
img_fname = '/tmp/temp_image.jpg'
img.save( img_fname)
with open( img_fname, 'rb') as fp:
img_file = MIMEImage( fp.read() )
img_file.add_header('Content-Disposition', 'attachment', filename=img_fname )
msg.attach( img_file)
...add other attachments and main body of email text...