Есть ли способ удалить электронное письмо в Gmail с IMAP на основе отправителя? - PullRequest
0 голосов
/ 09 июля 2020

Я работал над проектом, в котором я использовал IMAP для удаления всех сообщений от определенного отправителя.

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()

Этот код отлично работает, и он печатает слова «Удалить это» под любым сообщением от нежелательный отправитель. Есть ли функция, которую я мог бы определить или вызвать (она уже встроена в библиотеку IMAP), которая может решить мою проблему?

Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...