简体   繁体   中英

How to search for only emails containing attachments in poplib

I am trying to use poplib to search through emails and get only the ones with attachments, I have some current code but it's so slow as it downloads all the email messages, is there any way to just search the server for emails that have attachments and then download them?

def fetch_mail(delete_after=False):
    pop_conn = mail_connection()
    print("connected")
    messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
    messages = ["\n".join(mssg[1]) for mssg in messages]
    messages = [parser.Parser().parsestr(mssg) for mssg in messages]
    if delete_after == True:
        delete_messages = [pop_conn.dele(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
    pop_conn.quit()
    return messages


allowed_mimetypes = ["text/plain"]


def get_attachments():
    messages = fetch_mail()
    attachments = []
    for msg in messages:
        for part in msg.walk():
            if part.get_content_type() in allowed_mimetypes:
                name = part.get_filename()
                data = part.get_payload(decode=True)
                if name != None:
                    ranint = random.randint(100000,999999)
                    f = open(str(ranint) + name, 'wb')
                    f.write(data)
                    f.close()
                    attachments.append(name)
            else:
                continue
    return attachments```

The POP3 protocol does not support searching or any other feature which might allow you to determine which messages have attachments. If you are stuck with POP3, you are out of luck.

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