Python IMAP TypeError: 'Nonetype' Object Is Not Subscriptable

Python IMAP TypeError: 'Nonetype' Object Is Not Subscriptable

我正在使用 imap 检查与特定主题匹配的未读电子邮件。当我从我的测试电子邮件中收到一封电子邮件时,一切正常,但是当它来自一个我需要它来检查电子邮件的自动系统时,我收到一条错误消息,指出 'Nonetype' object is not subscriptable. 以下是我的代码:

import imaplib, time, email, mailbox, datetime
server = "imap.gmail.com"
port = 993
user = "Redacted"
password = "Redacted"

def main():
    while True:            
        conn = imaplib.IMAP4_SSL(server, port)
        conn.login(user, password)
        conn.list()
        conn.select('inbox', readonly=True)
        result, data = conn.search(None, '(UNSEEN SUBJECT "Alert: Storage Almost At Max Capacity")')
        i = len(data[0].split())

        for x in range (i):
            latest_email_uid = data[0].split()[x]
            result, email_data = conn.uid('fetch', latest_email_uid, '(RFC822)')
            raw_email = email_data[0][1] #This is where it throws the error
            raw_email_string = raw_email.decode('utf-8')
            email_message = email.message_from_string(raw_email_string)
            date_tuple = email.utils.parsedate_tz(email_message['Date'])
            local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
            local_message_date = "%s" %(str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))
            for part in email_message.walk():
                if part.get_content_type() == "text/plain":
                    body = part.get_payload(decode=True)
                    body = body.decode('utf-8')
                    body = body.split()
                    #Do some stuff
        conn.close()

if __name__ == "__main__":
    main()

回溯如下:

Traceback (most recent call last):
    File "TestEmail.py", line 200, in <module>
        main()
    File "TestEmail.py", line 168, in main
        raw_email = email_data[0][1]
TypeError: 'NoneType' object is not subscriptable.

我不明白为什么这在从某人的电子邮件发送的电子邮件中有效,但在我的系统通过电子邮件向我发送警报时却无效。有什么明显的解决方法吗?

编辑:我试过打印 resultemail 变量。以下是他们的输出:

Result: OK
Email: [None]

而如果我针对同一主题的电子邮件测试脚本,但从我的测试电子邮件发送,result 仍然是 "OK",但包含一封电子邮件。

编辑#2:我注意到电子邮件的格式有点不同。接受良好的是 text/plaintext/html,而未接受的是 text/plainContent-Transfer-Encoding: 7-bit。我该如何补救?如果我通过过滤器转发电子邮件并检查从过滤器接收的电子邮件,我的代码就可以正常工作。但是,我不想为此使用多个电子邮件。

您正在搜索消息序列号,并通过uid 获取。 如果你要使用conn.uid('fetch'),你必须同时使用conn.uid('search'),否则你就是在找苹果和摘橘子。

因此,由于并非所有 MSN 都是 UID,您偶尔会获取不存在的消息,这不是错误,但它不会 return 给您任何东西。