2

如何将电子邮件消息保存到文件而不加载到内存中?我用

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()

但是消息已加载到内存中。

4

1 回答 1

0

python 文档警告不要使用 POP3 协议。您的邮件服务器可能理解 IMAP,因此您可以使用IMAP4.partial()部分获取邮件,并将每个部分立即写入磁盘。

但是,如果您必须使用 POP3,那么您很幸运:POP3 协议是面向行的。Python的poplib库是纯python,看源码加个迭代器是小事一桩。我没有费心从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()
于 2013-05-11T16:44:23.397 回答