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

mor*_*n68 4 python email-attachments python-imaging-library

我在内存中有一个我创建的图像(使用 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...
Run Code Online (Sandbox Code Playgroud)

Nic*_*k T 5

MIMEImage表示第一个参数只是“包含原始图像数据的字符串”,因此您不必从文件中获取它open().read()

如果你在 PIL 中制作它并且没有直接序列化它的方法(可能没有,我不记得了),你可以使用一个io.StringIO(或BytesIO......无论哪个适用于MIMEImage真正想要的)文件 -像 buffer 一样保存文件,然后将其作为字符串读出。相关问题。现代化改编摘录:

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()
Run Code Online (Sandbox Code Playgroud)