I have written a program to read outlook emails using poplib and outputting only the filtered data into json and then deleting all the emails. But with the code I wrote It's not deleting all the emails and deleting only one email. Can anybody help me.
code:
def read_mail_from_pop3_server():
try:
conn = poplib.POP3_SSL(EMAIL_SERVER, 995)
print('Logging into Office365')
conn.user(EMAIL_USER)
conn.pass_(EMAIL_PASSWORD)
mail_count = len(conn.list()[1])
print("You have %d email messages." % mail_count)
output = []
for i in range(mail_count):
raw_email = b"\n".join(conn.retr(i + 1)[1])
msg = email.message_from_string(raw_email)
items_list = msg.items()
dict_items = OrderedDict(items_list)
email_body = ''
if msg.is_multipart():
...
else:
...
dict_items.update({'Body': email_body})
dict_obj = TatvamObjDict.load_fromFile('MailJsonData.Json')
dict_obj.review.original_text = dict_items['Body'].lstrip() if 'Body' in dict_items else "".strip()
...
if "<[email protected]>" in dict_items.itervalues():
output.append(dict_obj)
with open('del_check.json', 'w') as f:
json.dump(output, f, indent=4, sort_keys=True)
f.write('\n')
# # deleting emails directly by email index(count)
conn.dele(mail_count)
conn.quit()
You just flag one message, with index
mail_count
for deletion (upon quit, by what the poplib docs says). You should indent that line to put it inside thefor
loop and then give it the proper message index.