首页 > 解决方案 > 有没有办法根据发件人使用 IMAP 删除 gmail 中的电子邮件?

问题描述

我正在做一个项目,我使用 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 库中)可以解决我的问题?

提前致谢。

标签: pythongmail-imap

解决方案


推荐阅读