attaching an image (or object) from memory to an email in python
我在内存中创建了一个图像(使用numpy和PIL),我想以编程方式将其附加到创建的电子邮件中。 我知道我可以将其保存到文件系统中,然后重新加载/附加它,但是效率似乎很低:是否有一种方法可以将其仅通过管道传输到mime附件而不进行保存?
保存/重新加载版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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中制作它,并且没有直接序列化它的方法(可能没有,我想不起来了),则可以使用
1 2 3 4 5 6 7 8 9 | 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() |