小编Asi*_*tez的帖子

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)
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文档中找不到任何线索.

提前致谢.

python email smtplib python-3.x

10
推荐指数
1
解决办法
700
查看次数

标签 统计

email ×1

python ×1

python-3.x ×1

smtplib ×1