我有一段代码可以读取Outlook电子邮件并根据特定条件搜索电子邮件,但是问题是,一旦找到所有符合条件的电子邮件,该代码就不会停止。即使它什么也没返回,它仍然保持运行。
这是我到目前为止所拥有的:
我尝试使用break语句和多个if语句以及elif。但是我似乎无法使其正常工作。
import win32com.client
from datetime import date, timedelta
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(18).Folders.Item("Riscunit")
messages = inbox.Items
date = date.today() - timedelta(days=1)
subject = "Catalyst"
for message in messages:
if subject in message.subject and date == message.senton.date():
print(message.sender)
print(message.senton.date())
print(message.senton.time())
print(message.body)
elif subject != message.subject and date != message.senton.date:
break
我希望代码检索相关的电子邮件,然后停止运行。我是Python的新手,所以将不胜感激。
答案 0 :(得分:1)
elif
是不必要的,因为它与if
if
为假时做某事,那么else
会更合适-尽管您在这里可能不需要else
bag = ['pizza', 'ziplocks','bananas', 'milk glass', 'post-its','spray']
foods = {1:'pizza', 2:'bananas', 3:'milk'}
# check shopping bag for food
for item in bag:
for key in foods:
if foods[key] in item:
print('eat ' + foods[key]);
break
else:
print('put ' + item + ' away');
print("done");
这是另一个示例,当您的if条件不满足时,它会执行以下操作:
messages = [{'subject': 'shopping list', 'date': '05/10/2019', 'body': 'milk'},
{'subject': 'shopping list', 'date': '05/10/2019', 'body': 'pizza'},
{'subject': 'holiday', 'date': '12/10/2015', 'body': 'need vacation soon'},
{'subject': 'shopping list', 'date': '12/10/2015', 'body': 'we need potatoes'}]
date = '05/10/2019'
subject = "shopping list"
for item in messages:
for key in item:
if subject in item['subject'] and item['date'] == date:
print('buy ' + item['body']);
break
else:
print('archive \"' + item['body'] + '\" email');
break
print("done");
答案 1 :(得分:1)
您可能必须限制要测试的消息的数量,以查看它们是否是您想要的:
max = 42
for count, message in enumerate(messages):
if count > max:
break
if subject in message.subject and date == message.senton.date():
collect(message) # Do something with this message (print or append to list)
答案 2 :(得分:-1)
这可能是因为使用elif
而不是else
的逻辑。
尝试一下:
import win32com.client
from datetime import date, timedelta
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(18).Folders.Item("Riscunit")
messages = inbox.Items
date = date.today() - timedelta(days=1)
subject = "Catalyst"
for message in messages:
if subject in message.subject and date == message.senton.date():
print(message.sender)
print(message.senton.date())
print(message.senton.time())
print(message.body)
else:
subject != message.subject and date != message.senton.date
break