Python - 如何在不一次将整个文件加载到内存中的情况下发送带有附件的电子邮件



我想在低 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)
使用

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

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

有没有办法使用标准库(电子邮件和 smtplib(执行此操作(发送附件而无需一次加载整个文件(????我在 python 文档中找不到任何线索。

提前谢谢。

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

您不必使用公有存储桶,您可以对附件名称进行模糊处理,并添加一个"预签名"URL - 该网址仅在有限的时间内有效:https://docs.aws.amazon.com/code-samples/latest/catalog/python-s3-generate_presigned_url.py.html

最新更新