Python - 如何发送带附件的电子邮件而不立即将整个文件加载到内存中?

Asi*_*tez 10 python email smtplib python-3.x

我想在低RAM的VPS中发送10MB或更多附件的电子邮件; 在Python 3中发送带附件的电子邮件的常用方法(我发现)是这样的:

from email.message import EmailMessage
# import other needed stuff here omitted for simplicity
attachment = 'some_file.tar'
msg = EmailMessage()
# set from, to, subject here
# set maintype, subtype here
with open(attachment, 'rb') as fd:
    msg.add_attachment(fd.read(),  # this is the problem, the whole file is loaded
                       maintype=maintype,
                       subtype=subtype,
                       filename=attachment)
# smtp_serv is an instance of smtplib.SMTP
smtp_serv.send_message(msg)
Run Code Online (Sandbox Code Playgroud)

使用这种方法,整个文件被加载到内存中,然后使用smtplib.SMTP.send_message发送EmailMessage对象,我期望的是一种给add_attachment提供文件描述符(或可迭代)而不是文件内容的方法,当附件被发送到服务器时,以惰性方式(例如逐行或一些固定数量的字节)读取,例如:

with open('somefile') as fd:
    msg.add_attachment(fd, maintype=mt, subtype=st, filename=fn)
    smtp_serv.send_message(msg)
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点(发送一个附件,而不是一次加载整个文件)与标准库(电子邮件和smtplib)???? 我在python文档中找不到任何线索.

提前致谢.

rot*_*ten 1

我的建议是将附件上传到 S3 存储桶或 Google Storage 存储桶,然后在电子邮件中提供 URL 供收件人下载。大多数邮件服务器都会限制附件的大小,因此它们不太可能到达大多数邮件客户端。

您不必使用公共存储桶,您可以混淆附件名称,并添加“预先签名”的 url - 仅在有限的时间内有效: https: //docs.aws.amazon.com/code-样本/最新/目录/python-s3-generate_presigned_url.py.html