【发布时间】:2019-08-12 23:56:39
【问题描述】:
我正在使用 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.
我不明白为什么这会在从某人的电子邮件发送的电子邮件中起作用,但当我的系统通过电子邮件向我发送警报时却不起作用。有什么明显的解决办法吗?
编辑:我尝试打印 result 和 email 变量。以下是他们的输出:
Result: OK
Email: [None]
而如果我针对具有相同主题但从我的测试电子邮件发送的电子邮件测试脚本,result 仍然“正常”,但包含一封电子邮件。
EDIT#2:我注意到电子邮件的格式有些不同。接收良好的是text/plain 和text/html,而未被接收的是text/plain 和Content-Transfer-Encoding: 7-bit。我该如何补救?如果我通过过滤器转发电子邮件并检查从过滤器接收的电子邮件,我的代码就可以正常工作。但是,我不想为此使用多封电子邮件。
【问题讨论】:
标签: python-3.x imaplib