I'm very new at coding and this is my first real attempt to do anything like this. I want to print out multiple email bodies, that are at least two weeks old. (later on in my finished program, i want to make this changeable)
I've looked around other similar post but i just couldn't get it to work. The code i've posted is how far i've come at the moment. I can print out the latest email just fine, but how do i go on from this?
import imaplib
import sys
mail = imaplib.IMAP4_SSL('Server')
mail.login('User', 'Password')
mail.select('Inbox')
result, data = mail.uid('search', None, 'ALL')
ids = data[0]
id_list = ids.split()
latest_email_uid = int(id_list[-1])
for i in range(latest_email_uid, latest_email_uid-5, -1):
result, data = mail.uid('fetch', i, '(RFC822)')
raw_email = data[0][1]
import email
email_message = email.message_from_string(raw_email)
print email_message.get_payload(decode = True)
def get_first_text_block(self, email_message_instance):
maintype = email_message_instance.get_content_maintype()
if maintype == 'multipart':
for part in email_message_instance.get_payload():
if part.get_content_maintype() == 'text':
return part.get_payload
elif maintype == "text":
return email_message_instance.get_payload()
Thank you!
UPDATE New code!
import imaplib
import sys
import email
mail = imaplib.IMAP4_SSL('server')
mail.login('user', 'password')
mail.select('Inbox')
result, data = mail.uid('search', None, 'ALL')
ids = data[0]
id_list = ids.split()
latest_email_uid = int(id_list[-1])
raw_emails = []
for i in range(latest_email_uid, latest_email_uid-5, -1):
result, data = mail.uid('fetch', i, '(RFC822)')
raw_emails.append(data[0][1])
for raw_email in raw_emails:
email_message = email.message_from_string(raw_email)
print email_message.get_payload(decode = True)
def get_first_text_block(self, email_message_instance):
maintype = email_message_instance.get_content_maintype()
if maintype == 'multipart':
for part in email_message_instance.get_payload():
if part.get_content_maintype() == 'text':
return part.get_payload
elif maintype == "text":
return email_message_instance.get_payload()
This is how it looks, i probably made some mistake which results in only one email body is printed. Help is much appreciated!