问题描述
通过从网络上的资源中学习和实验,我已经能够编写出一些代码.
I've been able to work out some code through some learning and experiments from resources on the web.
每当我的 Outlook 邮箱中有会议邀请时,我都会陷入困境.代码执行失败.
I'm stuck at a point that everytime an there is a meeting invite in my outlook mailbox. The code fails to execute.
寻找有关如何在 Python 中处理异常的指导.
Looking for guidance on how to handle the exception in Python.
import csv
import win32com.client
from datetime import datetime
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
# Create empty list to store results
data_set = list()
date_id = (datetime.today()).strftime('%Y%m%d') # Used to create the filename
#Iterating through email items in outlook folder
for message in messages:
if messages is not None:
if len(inbox.Items) > 0:
row = list()
row.append(message.Subject)
row.append(message.Categories)
row.append(message.Sender)
#row.append(message.Sender.Address)
row.append(message.To)
row.append(message.SentOn)
row.append(message.CC)
row.append(message.BCC)
# Stores the data in a list
data_set.append(row)
# Print out the result to a csv with headers
with open(date_id + "_"+ 'outlook_Data.csv', 'w', newline='', encoding='utf-8') as csv_file:
headers = ['Subject', 'Category', 'From', 'To', 'Sent On', 'CC', 'BCC']
wr = csv.writer(csv_file, delimiter=',')
wr.writerow(headers)
for line in data_set:
wr.writerow(line)
推荐答案
这个问题归结为一个过滤问题:我们有一个不同类型的对象列表,其中一些不能被处理.
This problem reduces to a filtering problem: we have a list of objects of different types, some of which must not be processed.
就本回答而言,让收件箱中的电子邮件对象为 Message
类型,会议邀请为 MeetingInvitation
类型.
For the purposes of this answer, let the email objects in the inbox be of type Message
, and the meeting invitations be of type MeetingInvitation
.
这四种方法中的任何一种都可以应用.
Any of these four approaches can be applied.
尝试/除外/继续
try/except/continue
for message in messages:
row = list()
try:
row.append(message.Subject)
row.append(message.Categories)
row.append(message.Sender)
...
# Stores the data in a list
data_set.append(row)
except AttributeError as ex:
print('Error', ex, 'skipping message', message)
continue
检查循环顶部对象的类型
Check the type of the object at the top of the loop
for message in messages:
if isinstance(message, MeetingInvitation):
continue
row = list()
使用 filter 内置函数
filtered_messages = filter(lambda msg: not isinstance(msg, MeetingInvitation), messages)
for message in filtered_messages:
row = list()
...
使用列表理解(如果有 lot 的消息,生成器理解会更有效 - 将 []
替换为 ()
)
Use a list comprehension (If there are a lot of messages, a generator comprehension would be more efficient - replace []
with ()
)
filtered_messages = [msg for msg in msgs if not isinstance(msg, MeetingInvitation)]
for message in filtered_messages:
row = list()
...
可以反转 isinstance 检查以排除任何不是Message
The isinstance checks could be reversed to exclude anything that isn't a Message
if not isinstance(message, Message):
continue
或扩展以排除其他有问题的类型
or extended to exclude other problematic types
if isinstance(message, (MeetingInvitation, SomethingElse)):
continue
所有四种方法在功能上都是等效的.在我看来,过滤器和列表理解方法更简洁,因为它们将过滤过程与实际的消息处理分开.
All of the four approaches are functionally equivalent. The filter and list comprehension approaches are cleaner, in my opinion, because they separate the filtering process from the actual message processing.
这篇关于如果存在会议邀请,则使用 Python 从 Outlook 读取电子邮件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!