Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将图像(或对象)从内存附加到电子邮件_Python_Python Imaging Library_Email Attachments - Fatal编程技术网

在python中将图像(或对象)从内存附加到电子邮件

在python中将图像(或对象)从内存附加到电子邮件,python,python-imaging-library,email-attachments,Python,Python Imaging Library,Email Attachments,我在内存中有一个我创建的图像(使用numpy和PIL),我想通过编程将其附加到创建的电子邮件中。我知道我可以将它保存到文件系统,然后重新加载/附加它,但这似乎很有效:有没有一种方法可以将它通过管道传输到mime附件而不保存 保存/重新加载版本: from PIL import Image from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart ...some img creati

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

保存/重新加载版本:

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...
第一个参数只是“一个包含原始图像数据的字符串”,因此您不必从文件中
打开()
,然后
读取()

如果您使用的是PIL,并且没有直接序列化的方法(可能没有,我想不起来),您可以使用(或
BytesIO
…使用
MIMEImage
真正需要的)文件缓冲区来保存文件,然后将其作为字符串读取。节选:

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()
可能重复的