[英]Check if email is read or unread using imaplib and python?
我想根据谁向我发送电子邮件以及它们是否已读或未读来过滤掉电子邮件,我还想在分析电子邮件后将它们标记为“已读”。
我想出了如何按谁发送它们进行过滤,如何找出已读/未读部分?
谢谢!
我正在使用此代码(在线找到):
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()
我看到你已经安装了 imap_tools lib,但是你没有使用它。 所以,你可以用它来达到你的目标。
from imap_tools import MailBox, AND
# get unseen emails sent by good@some.xx from INBOX folder
with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
# *mark emails as seen on fetch, see mark_seen arg
for msg in mailbox.fetch(AND(from_='good@some.xx', seen=False)):
print(msg.subject)
for att in msg.attachments:
print(att.filename)
body = msg.text or msg.html
关于“我如何找出已读/未读”,您可以:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.