python - 有没有办法根据发件人使用 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 库中)可以解决我的问题?
提前致谢。
解决方案
推荐阅读
- html - 如何让引导程序占据整个屏幕
- fortran - 根据输入从子程序中读取不同的文件
- html - flex 项目在换行之前缩小到最小宽度
- ubuntu - ubuntu 20.4.1 WSL2 和 AWS ubuntu 实例上的 Wireshark
- clojure - 在clojure中使用给定步骤迭代列表
- macos - SwiftUI 文本在编辑时随机上下颠倒
- spring-boot - 为什么必须在 AbstractMongoClientConfiguration 中指定数据库名称?
- javascript - 待办事项列表删除所有功能
- javascript - 正则表达式在多个方括号内返回内容
- php - 如何通过 FORM 将数据插入 MYSQL