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

末鹿安然 提交于 2019-12-06 04:25:51
Nick T

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