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

标签 python python-3.x email smtplib

我想在 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 发送 EmailMessage 对象,我期望的是一种为 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 Storage 存储桶,然后在电子邮件中提供一个 URL 供收件人下载。大多数邮件服务器都会限制附件的大小,因此它们不太可能通过大多数邮件客户端。

您不必使用公共(public)存储桶,您可以混淆附件名称,并添加“预签名”网址 - 仅在有限的时间内有效:https://docs.aws.amazon.com/code-samples/latest/catalog/python-s3-generate_presigned_url.py.html

关于Python - 如何在不一次将整个文件加载到内存的情况下发送带附件的电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47334185/

相关文章:

python - 在 Pandas 中更改多头/空头头寸的更有效方法

Python "if modified since"检测?

python - 迭代到多级 pandas DataFrame 的优雅方法

python-3.x - Pandas:过滤定期付款

html - 扩展模板不适用于 FOSUserBundle 电子邮件。交响乐2

java - 使用 JavaMail 发送带有附件的邮件 - 写入 Multipart 时出现异常

python - 使用python将excel文件中的数据导入SQL Server

python - 寻找不匹配模式的效率

PHP 电子邮件不以 html 格式发送

python - 基于groupby过滤pandas数据框(仅前3个)