有没有一种方法可以根据发件人删除带有IMAP的gmail电子邮件?

时间:2020-07-09 04:17:19

标签: python gmail-imap

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

谢谢。

0 个答案:

没有答案