imaplib读取的不是最新的emai

2024-06-06 18:58:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个邮箱,我需要阅读来自python的邮件。邮件服务器支持IMAP访问,所以我尝试使用python内置模块imaplib
我的代码:

import imaplib

def ReadLatest():
    m = imaplib.IMAP4_SSL(<server>)
    m.login(<login>, <password>) # ('OK', ['LOGIN Completed.'])
    if result != 'OK':
        raise Exception("Error connecting to mailbox: {}".format(data))

    result, data = m.select("inbox") # ('OK', ['N']) N - count inbox
    if result != 'OK':
        raise Exception("Error reading inbox: {}".format(data))
    if data == ['0']:
        return None

    #result, data = m.search(None, "ALL") # ('OK', ['1 2']) - numbers of mails
    #m.sort('REVERSE DATE', 'UTF-8', 'ALL') # <-- ERROR!

    latest = data[0].split()[-1]
    result, data = m.fetch(latest, "(RFC822)")
    if result != 'OK':
        raise Exception("Error reading email: {}".format(data))
    <...>
    # further e-mail processing

所以,我的问题是:当我执行上面的代码时,它不会读取最新的电子邮件,以防同时接收到少量最近的邮件。我正在通过网络界面查看。
当我按日期排序时,我遇到了一个错误:{error}SORT command error: BAD ['Command syntax error, sc=...']。它不是gmail邮箱,我知道它不支持sort命令。我不知道我的邮箱是否支持它,也不知道如何检查它。在


Tags: 代码formatdataifexception邮件loginok