我有一个迭代邮箱的函数:
def iterate_box(imap):
#[...]
status, messages = imap.select("INBOX")
total_messages = int(messages[0])
N = 10000
for i in range(total_messages, total_messages - N, -1):
# Fetch the email message by ID
res, msg = imap.fetch(str(i), "(RFC822)")
for response in msg:
if isinstance(response, tuple):
msg = email.message_from_bytes(response[1])
# [...] A few processes
is_responded = send_my_email(receivers, subject, message)
if is_responded:
delete_mail(imap,uid)
else:
print("Not responded, I keep the mail")
只有在
is_responded
的情况下我才想删除邮件。我的问题是我必须指定 UID 才能删除邮件:
def delete_email_by_uid(imap, uid):
# Search for emails with the given UID
result, data = imap.uid("search", None, f"UID {uid}")
if result == "OK":
email_ids = data[0].split()
if email_ids:
# Mark the email for deletion
mail.uid("store", email_ids[0], "+FLAGS", "\\Deleted")
# Permanently remove the email
mail.expunge()
print("Email deleted successfully.")
else:
print("No email found with the provided UID.")
else:
print("Error searching for email.")
# Logout and close the connection
mail.logout()
我无法在
iterate_box
函数上迭代 UID。如何将 i
的索引 (iterate_box
) 与消息的 UID“链接”,以便传递到我的 delete_email_by_uid
函数。
我精确地说,我有义务在 iterate_box
函数中迭代索引。
def delete_email_by_uid(imap, uid):
# Search for emails with the given UID
result, data = imap.uid("search", None, f"UID {uid}")
if result == "OK":
email_ids = data[0].split()
email_ids = [email_id.decode("utf-8") for email_id in email_ids]
for email_id in email_ids:
# Follow your programm
# email_ids is your list of UID
# email_id is the current selected UID of your programm