将内存中的图像(或对象)附加到python中的电子邮件 [英] attaching an image (or object) from memory to an email in python

查看:68
本文介绍了将内存中的图像(或对象)附加到python中的电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在内存中创建了一个图像(使用numpy和PIL),我想以编程方式将其附加到创建的电子邮件中.我知道我可以将其保存到文件系统中,然后重新加载/附加它,但是效率似乎很低:是否有一种方法可以不保存而仅将其通过管道传递给mime附件?

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?

保存/重新加载版本:

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

推荐答案

MIMEImage,第一个参数只是包含原始图像数据的字符串",因此您不必从文件中先open()然后.read().

如果要在PIL中制作它,并且没有直接序列化它的方法(可能没有,我不记得了),则可以使用相关问题.现代化改编摘录:

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

这篇关于将内存中的图像(或对象)附加到python中的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆