如何用Python统计近7天Outlook中按错误类型与服务器分类的邮件数量
Fixing Your Outlook Email Statistics Code for Error & Server Counts
Hey there! As a fellow Python learner, I get how tricky it can be to get started with Outlook automation. Let's fix up your code to properly count those emails grouped by error type and server name. First, let's go over the issues in your current code, then build a working version.
Issues in Your Current Code
- Undefined variable
s1: You're trying to prints1in the loop, but this variable isn't defined anywhere. You probably meant to printsubjectortime. - Missing counting logic: Right now, you're just iterating through emails without tracking how many match each error + server combination.
- Duplicate server entries: Your
serverlist has duplicate entries (TEST-AUDBappears twice), which would lead to redundant checks. - Potential date format issues: Outlook's
Restrictmethod can be picky about date formats—your current format might not work depending on your system's regional settings. - No matching between error types and servers: There's no code to check if an email's subject contains both a specific error type and server name.
Working Corrected Code
import win32com.client import datetime as dt from collections import defaultdict # Initialize Outlook connection outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.Folders.Item(2).Folders['Inbox'] messages = inbox.Items messages.sort("[ReceivedTime]", True) # Sort newest first # Define your error types and unique servers error_types = [ 'There are errors in the SQL Error Log on', 'Check for missing backups on', 'Check drive space on', 'Check memory usage on', 'Check deadlock on ' ] servers = ['TEST-AUDB', 'EUDB', 'TEST-EUDB', 'PROD-AUDB', 'PROD-EUDB'] # Removed duplicate TEST-AUDB # Set date range: last 7 days seven_days_ago = dt.datetime.now() - dt.timedelta(days=7) # Format date correctly for Outlook Restrict (adjust format if needed for your region) date_filter = seven_days_ago.strftime('%Y-%m-%d %H:%M:%S') filtered_messages = messages.Restrict(f"[ReceivedTime] >= '{date_filter}'") # Initialize a dictionary to track counts: key = (error_type, server), value = count email_counts = defaultdict(int) # Iterate through filtered emails for msg in filtered_messages: subject = msg.Subject received_time = msg.ReceivedTime # Check each error type and server combination in the subject for error in error_types: if error in subject: # Now check which server is mentioned for server in servers: if server in subject: email_counts[(error, server)] += 1 break # Stop checking servers once we find a match # Print the results print("Email Statistics (Last 7 Days):") print("-" * 80) for (error, server), count in email_counts.items(): print(f"Error Type: '{error}' | Server: {server} | Count: {count}") # Optional: Print total emails processed print(f"\nTotal emails processed: {len(filtered_messages)}")
Key Improvements Explained
defaultdictfor counting: This makes it easy to track counts without manually initializing every possible error+server combination.- Unique server list: Removed duplicates to avoid redundant checks.
- Robust date filtering: Used a date format that's more widely compatible with Outlook's
Restrictmethod. If this doesn't work for your region, try'%m/%d/%Y %H:%M %p'instead. - Subject matching logic: For each email, we first check if it contains an error type, then look for a server name in the same subject. This ensures we only count emails that have both.
- Clean output: The final print statement organizes the counts clearly by error type and server.
Troubleshooting Tips
- If your inbox isn't being found, double-check
outlook.Folders.Item(2)—the index might be different for your Outlook profile. You can list all folders withfor i, folder in enumerate(outlook.Folders): print(i, folder.Name)to find the correct index. - If no emails are being filtered, verify the date format matches what Outlook expects. You can test the filter string with a known email's received time.
- For more precise matching (e.g., avoiding partial server names), you could use regular expressions instead of
in. For example:re.search(rf'\b{server}\b', subject)to match whole words only.
内容的提问来源于stack exchange,提问作者Bhupesh Pradhan
相关产品推荐
相关产品推荐

