Python+Outlook自动化脚本:发件人识别异常问题求助
Outlook自动化脚本发件人地址解析异常解决方法
问题背景
我需要实现一个Python脚本完成以下Outlook自动化操作:
- 读取邮件主题与内容,判断请求是否已确认
- 若请求未确认,回复邮件要求对方回应
- 若请求已确认,发送邮件告知操作已成功完成
但在识别发件人时遇到异常:普通@outlook.com邮箱能正常返回邮箱地址,但特定域名的发件人会显示为Exchange专有格式(如/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP (FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=D5C4A87552E64C4F879F178A9710A189- sender's name)。当前运行环境为Jupyter/Anaconda3,使用的代码如下:
import win32com.client from datetime import datetime, timedelta # Connect to Outlook outlook = win32com.client.Dispatch("Outlook.Application") namespace = outlook.GetNamespace('MAPI') # Access the Inbox inbox = namespace.GetDefaultFolder(6) # Function to search for emails containing any term from the list in the body or subject def mail_body_search(terms, folder): term_counts = {term: 0 for term in terms} # Dictionary to store counts of each term relevant_messages = [] # List to store relevant emails senders = set() # Set to store unique sender emails # Filter emails that contain any term in the body or subject for message in folder.Items: # Iterate over items in the folder for term in terms: # Check each term in the list if term.lower() in message.Body.lower() or term.lower() in message.Subject.lower(): relevant_messages.append((message, message.Parent.Name)) # Add relevant email term_counts[term] += 1 # Increment count for the found term senders.add(message.SenderEmailAddress) # Add sender's email to the set break # If the term is found, no need to check other terms for this email return relevant_messages, term_counts, senders # Return the list of found emails, term counts, and unique senders # List of terms to search search_terms = ['Teste', 'Testing with python'] # Call the function to search for emails with any of the terms in the Inbox results, term_counts, senders = mail_body_search(search_terms, inbox) # Display the total number of emails found print(f'A total of {len(results)} emails were found.') # Display the number of emails found for each term for term, count in term_counts.items(): print(f'{count} emails were found for "{term}".') # Display the unique sender emails print('Unique sender emails:') for sender in senders: print(sender)
解决方案
出现该问题的原因是Exchange邮箱的发件人信息以DN(专有名称)格式存储,直接调用SenderEmailAddress会返回该格式而非实际邮箱地址。可以通过以下方式获取正确的邮箱地址:
核心思路
判断发件人地址类型:
- 若为
SMTP类型,直接使用SenderEmailAddress - 若为
EX类型,通过Sender.AddressEntry.GetExchangeUser()方法解析出实际邮箱地址
修改后的代码
添加一个辅助函数用于获取正确的发件人邮箱地址,并修改原函数中获取发件人信息的逻辑:
import win32com.client from datetime import datetime, timedelta # Connect to Outlook outlook = win32com.client.Dispatch("Outlook.Application") namespace = outlook.GetNamespace('MAPI') # Access the Inbox inbox = namespace.GetDefaultFolder(6) # 辅助函数:获取正确的发件人邮箱地址 def get_sender_email(message): try: if message.SenderEmailType == 'EX': exchange_user = message.Sender.AddressEntry.GetExchangeUser() if exchange_user: return exchange_user.PrimarySmtpAddress # 若无法获取Exchange用户信息,返回显示名称 return message.Sender.Name else: return message.SenderEmailAddress except Exception as e: # 异常情况下返回原始地址或显示名称 return message.SenderEmailAddress or message.Sender.Name # Function to search for emails containing any term from the list in the body or subject def mail_body_search(terms, folder): term_counts = {term: 0 for term in terms} # Dictionary to store counts of each term relevant_messages = [] # List to store relevant emails senders = set() # Set to store unique sender emails # Filter emails that contain any term in the body or subject for message in folder.Items: # Iterate over items in the folder # 跳过非邮件项(如会议邀请等) if message.Class != 43: continue for term in terms: # Check each term in the list if term.lower() in message.Body.lower() or term.lower() in message.Subject.lower(): relevant_messages.append((message, message.Parent.Name)) # Add relevant email term_counts[term] += 1 # Increment count for the found term sender_email = get_sender_email(message) senders.add(sender_email) # Add sender's email to the set break # If the term is found, no need to check other terms for this email return relevant_messages, term_counts, senders # Return the list of found emails, term counts, and unique senders # List of terms to search search_terms = ['Teste', 'Testing with python'] # Call the function to search for emails with any of the terms in the Inbox results, term_counts, senders = mail_body_search(search_terms, inbox) # Display the total number of emails found print(f'共找到 {len(results)} 封邮件。') # Display the number of emails found for each term for term, count in term_counts.items(): print(f'包含 "{term}" 的邮件有 {count} 封。') # Display the unique sender emails print('唯一发件人邮箱:') for sender in senders: print(sender)
关键修改点
- 新增
get_sender_email函数,处理Exchange和SMTP两种类型的发件人地址解析 - 在遍历邮件时增加
message.Class != 43判断,跳过非邮件类型的项目(如会议请求、任务等),避免不必要的错误 - 将原代码中直接添加
message.SenderEmailAddress改为调用get_sender_email获取正确地址
内容的提问来源于stack exchange,提问作者duduzuero
相关产品推荐
相关产品推荐

