简体   繁体   中英

Problem with deleting emails using poplib

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 "<xyz@gmail.com>" 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 the for loop and then give it the proper message index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM