[英]python imaplib fetch result is none with simple email from gmail
i get None as a result for an email i wrote with Thunderbird or gmail webapp. 我用Thunderbird或gmail webapp写的电子邮件的结果是我什么也没有。
For example my subject is "myfancysubject" and the text is just "hello" 例如,我的主题是“ myfancysubject”,文本只是“ hello”
i get no data (NONE) by using imaplib fetch operation with 通过使用imaplib提取操作,我没有任何数据(无)
result, data = mail.fetch(latest_email_id, '(RFC822)') # fetch the email body (RFC822) for the given ID
my assumption is the mail has no RFC822 Tag ? 我假设邮件没有RFC822标签?
But how can i get the content of that mail ? 但是我如何获得该邮件的内容?
here is my full code: 这是我的完整代码:
import imaplib
import email
try:
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('email@gmail.com', 'password')
labels = mail.list()
# Out: list of "folders" aka labels in gmail.
inbox = mail.select("inbox") # connect to inbox.
#result, data = mail.search(None, "ALL")
result, data = mail.uid('search', None, '(HEADER Subject "myfancysubject")')
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = None
if len(id_list) == 1:
latest_email_id = id_list[0] # get the latest
pass
else:
latest_email_id = id_list[-1]
pass
result, data = mail.fetch(latest_email_id, '(RFC822)') # fetch the email body (RFC822) for the given ID
print(data)
raw_email = data[0][0]
email_message = email.message_from_string(raw_email)
print email_message['To']
print email.utils.parseaddr(email_message['From'])
print email_message.items() # print all headers
except Exception:
print('Ex')
Got the solution, You have to be consistent in using uid or sequential id 得到了解决方案,您必须在使用uid或顺序ID时保持一致
Instead of using 而不是使用
result, data = mail.fetch(latest_email_id, '(RFC822)')
I had to use : 我不得不使用:
result, data = mail.uid('fetch', latest_email_id, '(RFC822)')
As previously you had searched through UID instead of the sequence id. 如前所述,您已经搜索了UID而不是序列ID。 Then later you were trying to get RFC822 or body of mail by sequence id (default).
然后,稍后您尝试通过序列ID(默认值)获取RFC822或邮件正文。
You were trying to get sequence id x instead of uid x. 您试图获取序列ID x而不是uid x。 These two differ when some mail has been deleted in between.
当两者之间的某些邮件被删除时,这两者是不同的。
It was perhaps giving none because the mail with that se might have been deleted or something. 可能没有任何结果,因为带有该se的邮件可能已被删除或其他内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.