如何在不加载到内存的情况下将电子邮件保存到文件中? 我用
import poplib
pop_conn = poplib.POP3(servername)
pop_conn.user(username)
pop_conn.pass_(passwd)
msg = pop_conn.retr(msg_number)[1]
msg_text = '\n'.join(msg)
msg_file = open(msg_file_name, ,"wb")
msg_file.write(msg_text)
msg_file.close()
但是消息已加载到内存中。
答案 0 :(得分:0)
python docs caution反对使用POP3协议。您的邮件服务器可能理解IMAP,因此您可以使用IMAP4.partial()来获取部分邮件,立即将每个部分写入磁盘。
但如果您 使用POP3,那么您很幸运:POP3协议是面向行的。 Python的poplib库是纯python,通过查看the source来添加迭代器是一件小事。我没有费心从POP3
类派生,所以这里是如何通过猴子修补来实现的:
from poplib import POP3
def iretr(self, which):
"""
Retrieve whole message number 'which', in iterator form.
Return content in the form (line, octets)
"""
self._putcmd('RETR %s' % which)
resp = self._getresp() # Will raise exception on error
# Simplified from _getlongresp()
line, o = self._getline()
while line != '.':
if line[:2] == '..':
o = o-1
line = line[1:]
yield line, o
line, o = self._getline()
POP3.iretr = iretr
然后,您可以一次获取邮件并写入磁盘一行,如下所示:
pop_conn = POP3(servername)
...
msg_file = open(msg_file_name, "wb")
for line, octets in pop_conn.iretr(msg_number):
msg_file.write(line+"\n")
msg_file.close()