0

I was working on a project where I used IMAP to delete all messages from a particular sender.

import email
from email.header import decode_header
import webbrowser
import os

# account credentials
username = "my email"
password = "my pass"

imap = imaplib.IMAP4_SSL("imap.gmail.com")
#imap is commonly used with gmail, however there are variants that are able to interface with outlook

imap.login(username, password)

status, messages = imap.select("INBOX")

N = 6

messages = int(messages[0])



for i in range(messages, messages-N, -1):
    # fetch the email message by ID
    res, msg = imap.fetch(str(i), "(RFC822)")
    for response in msg:
        if isinstance(response, tuple):
            # parse a bytes email into a message object
            msg = email.message_from_bytes(response[1])
            # decode the email subject
            subject = decode_header(msg["Subject"])[0][0]
            if isinstance(subject, bytes):
                # if it's a bytes, decode to str
                subject = subject.decode()
            # email sender
            from_ = msg.get("From")
            print("Subject:", subject)
            print("From:", from_)
            if "Unwanted sender" in from_:
                print("Delete this")
            # if the email message is multipart
            if msg.is_multipart():
                # iterate over email parts
                for part in msg.walk():
                    # extract content type of email
                    content_type = part.get_content_type()
                    content_disposition = str(part.get("Content-Disposition"))
                    try:
                        # get the email body
                        body = part.get_payload(decode=True).decode()
                    except:
                        pass
                    if content_type == "text/plain" and "attachment" not in content_disposition:
                        # print text/plain emails and skip attachments
                        print(body)
                        print("=" * 100)
            else:
                # extract content type of email
                content_type = msg.get_content_type()
                # get the email body
                body = msg.get_payload(decode=True).decode()
                if content_type == "text/plain":
                    # print only text email parts
                    print(body)


imap.close()
imap.logout()

This code works perfectly fine, and it prints the words "Delete this" under any message from the unwanted sender. Is there a function I could define or call upon (thats already built into the IMAP library) that can solve my problem?

Thanks in advance.

  • 2
    Does this answer your question? [Using python imaplib to "delete" an email from Gmail?](https://stackoverflow.com/questions/1777264/using-python-imaplib-to-delete-an-email-from-gmail) – SiHa Jul 09 '20 at 04:30
  • why not getting the messages from X sender with the Gmail API using [Users.messages: list](https://developers.google.com/gmail/api/v1/reference/users/messages/list)? – Kessy Jul 09 '20 at 10:06

0 Answers0