【发布时间】:2020-11-18 15:55:54
【问题描述】:
我想根据发给我的电子邮件以及它们是否已读或未读来过滤掉电子邮件,我还想在分析后将电子邮件标记为“已读”。
我想出了如何按谁发送它们进行过滤,我如何找出已读/未读部分?
谢谢!
我正在使用此代码(在线找到):
import imaplib
import email
from email.header import decode_header
import webbrowser
import os
import pprint
from imap_tools import MailBox, Q
username = input('Email: ')
password = input('Password: ')
# create an IMAP4 class with SSL
imap = imaplib.IMAP4_SSL("imap.gmail.com")
# authenticate
imap.login(username, password)
status, messages = imap.select("INBOX", readonly=True)
# number of top emails to fetch
N = 15
# total number of emails
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])
print(msg)
# 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
#print(msg.get("Seen"))
from_ = msg.get("From")
print("Subject:", subject)
print("From:", from_)
# if the email message is multipart
if msg.is_multipart() and ("email of interest" in from_):
# 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)
imap.close()
imap.logout()
【问题讨论】:
-
RFC3501 是(长)但内容丰富的阅读材料,您可以了解获取不同信息所需的内容。具体来说,您希望
.fetch('FLAGS')获取消息的标记元数据,并检查它的 \Seen 标志。 -
当我尝试时这对我有用,有没有办法将电子邮件标记为已读?
-
两种方式:您可以使用 STORE 来存储 \Seen 标志,或者您可以使用 FETCH BODY (no peek) 在获取时将其标记为已读。