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