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

浪尽此生 提交于 2019-12-10 10:56:13

问题


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

回答1:


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()


来源:https://stackoverflow.com/questions/27646065/attaching-an-image-or-object-from-memory-to-an-email-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!