Reputation: 15756
i get None as a result for an email i wrote with Thunderbird or gmail webapp.
For example my subject is "myfancysubject" and the text is just "hello"
i get no data (NONE) by using imaplib fetch operation with
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 ?
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 protected]', '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')
Upvotes: 2
Views: 3039
Reputation: 2384
Got the solution, You have to be consistent in using uid or sequential 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. Then later you were trying to get RFC822 or body of mail by sequence id (default).
You were trying to get sequence id x instead of 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.
Upvotes: 4