在 python 中仅搜索新电子邮件的优雅方法是什么?

问题描述 投票:0回答:2

我正在使用 imaplib 来访问 Python 脚本的电子邮件。我想搜索上次运行脚本后收到的所有电子邮件。

mail.search(None,'(FROM "[email protected]" SUBJECT "xyz" SINCE {last_timestamp})')

不幸的是,搜索忽略时间,只考虑日期。因此,如果某些旧电子邮件是在last_timestamp同一天收到的,即使它们早于确切时间,也会检索到这些旧电子邮件。

作为解决方法,我存储电子邮件 ID 并从搜索结果中删除旧的电子邮件 ID。我想知道是否有更优雅的解决方案。

python imap gmail-api imaplib
2个回答
0
投票

尝试寻找看不见的东西

# Select an email folder
inbox = box["INBOX"]

# Search and process messages
for msg in inbox.search(unseen=True):

0
投票

您可以使用

fetch
方法检索每封电子邮件的
INTERNALDATE
,然后根据确切时间进行过滤。

类似这样的:

import imaplib
import email
from datetime import datetime

# Connect to your mailbox
imap_server = 'imap.example.com'
username = 'your_username'
password = 'your_password'
mailbox = 'INBOX'

imap = imaplib.IMAP4_SSL(imap_server)
imap.login(username, password)
imap.select(mailbox)

# Define the search criteria
from_email = '[email protected]'
subject = 'xyz'
last_timestamp = '2023-08-22 12:00:00'  # Replace with your last timestamp

# Search for emails based on the criteria
search_criteria = f'(FROM "{from_email}" SUBJECT "{subject}" SINCE "{last_timestamp}")'
status, email_ids = imap.search(None, search_criteria)

if status == 'OK':
    email_id_list = email_ids[0].split()
    new_emails = []

    # Iterate through the email IDs and fetch the INTERNALDATE
    for email_id in email_id_list:
        status, email_data = imap.fetch(email_id, '(INTERNALDATE)')
        if status == 'OK':
            # Parse the INTERNALDATE and convert it to a datetime object
            internal_date_str = email_data[0].split()[1].decode('utf-8')
            internal_date = datetime.strptime(internal_date_str, '%d-%b-%Y %H:%M:%S %z')

            # Compare the INTERNALDATE with the last timestamp
            if internal_date > datetime.strptime(last_timestamp, '%Y-%m-%d %H:%M:%S'):
                new_emails.append(email_id.decode('utf-8'))

    # Now, new_emails contains the email IDs of emails received after the last timestamp
    print("New email IDs:", new_emails)

imap.logout()

请注意,

INTERNALDATE
可能位于不同的时区,因此请务必调整您的时间戳

© www.soinside.com 2019 - 2024. All rights reserved.