morvan68
morvan68

Reputation: 682

attaching an image (or object) from memory to an email in python

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...

Upvotes: 4

Views: 4696

Answers (1)

Nick T
Nick T

Reputation: 26717

MIMEImage says that the first argument is just "a string containing the raw image data", so you don't have to open() then .read() it from a file.

If you're making it in PIL and there isn't a way to serialize it directly (there might not be, I can't recall), you can use a io.StringIO (or BytesIO...whichever works with what MIMEImage really wants) file-like buffer to save the file, then read it out as a string. Related question. Modernized adapted excerpt:

import io
from email.mime.image import MIMEImage

# ... make some image

outbuf = io.StringIO()
image.save(outbuf, format="PNG")
my_mime_image = MIMEImage(outbuf.getvalue())
outbuf.close()

Upvotes: 5

Related Questions