You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python实时获取或在未来1小时内持续获取Outlook邮件

Hey there! Let's work through this problem together—since you're just starting out with programming, we'll keep things clear and straightforward.

The issue with your current code is that it only grabs the very last email once and exits. To make it run continuously for hours and pick up new emails as they come in, we'll add a loop that checks for new messages regularly, tracks which ones we've already processed, and handles each new email as it arrives.

Here's a modified version of your code that does exactly that:

import win32com.client
import re
from selenium import webdriver
from selenium.webdriver.common.by import By  # Don't forget this if you use element selectors
from datetime import datetime, timedelta
import time

def process_single_email(message):
    """Wrap your email processing logic in a reusable function"""
    body_content = message.Body
    
    # --- Your regular expression code goes here ---
    # Example: Extract a specific value from the email body
    # pattern = r"Your Regex Pattern Here"
    # match_result = re.search(pattern, body_content)
    # if match_result:
    #     extracted_info = match_result.group(1)
    
    # --- Your Selenium form-filling code goes here ---
    # Example (adjust to your form's structure):
    # driver = webdriver.Chrome()
    # driver.get("https://your-form-url.com")
    # driver.find_element(By.ID, "target-input").send_keys(extracted_info)
    # ... complete form submission steps ...
    # driver.quit()  # Or keep driver open if processing multiple emails
    
    print(f"Successfully processed email received at: {message.ReceivedTime}")

if __name__ == "__main__":
    # Connect to Outlook and target your specific folder
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    target_folder = outlook.Folders['keelanur.nishanth@nxp.com'].Folders['Inbox'].Folders['NXDI Maintenace LSF']
    
    # Initialize email list and sort by received time (newest first)
    messages = target_folder.Items
    messages.Sort("[ReceivedTime]", True)
    
    # Set a baseline for already processed emails
    last_processed_time = datetime.now()
    if messages.Count > 0:
        last_processed_time = messages.GetLast().ReceivedTime
        # Optional: Process the initial last email if you haven't already
        process_single_email(messages.GetLast())
    
    # How long you want the program to run (adjust hours as needed)
    total_run_hours = 5
    end_time = datetime.now() + timedelta(hours=total_run_hours)
    
    print(f"Started monitoring for new emails. Will stop at {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # Loop to check for new emails until the end time
    while datetime.now() < end_time:
        try:
            # Refresh the messages list to avoid Outlook cache issues
            messages = target_folder.Items
            messages.Sort("[ReceivedTime]", True)
            
            # Filter for emails received after our last processed time
            new_emails = [email for email in messages if email.ReceivedTime > last_processed_time]
            
            # Sort new emails by received time (oldest first) to process in order
            new_emails.sort(key=lambda x: x.ReceivedTime)
            
            # Process each new email
            for email in new_emails:
                process_single_email(email)
                # Update our baseline to the latest processed email's time
                if email.ReceivedTime > last_processed_time:
                    last_processed_time = email.ReceivedTime
            
            # Wait before checking again (adjust seconds as needed)
            time.sleep(60)  # Check every 1 minute
            
        except Exception as e:
            print(f"Oops, an error popped up: {str(e)}")
            # Wait a bit longer before retrying if something goes wrong
            time.sleep(30)
    
    print("Email monitoring finished!")

Key things to note:

  • Reusable function: process_single_email keeps your email handling logic clean and easy to update.
  • Tracking processed emails: The last_processed_time variable ensures we never reprocess the same email twice.
  • Continuous loop: The while loop runs until your specified end time (we set it to 5 hours, but you can change total_run_hours to whatever you need).
  • Regular checks: time.sleep(60) makes the program wait 1 minute between checks—you can shorten or lengthen this based on how quickly you need to catch new emails.
  • Error handling: The try/except block prevents small issues (like Outlook glitches) from crashing the whole program.

Quick tips for testing:

  • When you first test, set total_run_hours to a small value (like 0.1 for 6 minutes) to avoid waiting too long.
  • For Selenium, if you're processing multiple emails, consider keeping the browser open between emails instead of opening/closing it every time—it'll be faster.

内容的提问来源于stack exchange,提问作者KEELANUR NISHANTH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:12:27