我已经编写了一个简短的代码来下载和重命名outlook帐户中特定文件夹中的文件。代码运行得很好,唯一的问题是我通常需要运行代码几次才能真正下载所有消息。似乎代码只是没有确认一些消息,当我运行它时没有错误。 我尝试过一些方法,比如在python窗口中一步一步地遍历每一行,在关闭或打开outlook的情况下运行代码,以及在成功保存文件后打印文件,以查看是否有导致问题的特定消息。 这是我的密码
#! python3
# downloadAttachments.py - Downloads all of the weight tickets from Bucky
# Currently saves to desktop due to instability of I: drive connection
import win32com.client, os, re
#This line opens the outlook application
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
#Not exactly sure why the inbox is default folder 6 but it works
inbox = outlook.GetDefaultFolder(6)
#box where the messages are to save
TicketSave = inbox.Folders('WDE').Folders('SAVE').Folders('TicketSave')
#box where the messages are moved to
done = inbox.Folders('WDE').Folders('CHES').Folders('Weight Tickets')
ticketMessages = TicketSave.Items
#Key is used to verify the subject line is correct. This script only works if the person sends
# their emails with a consistent subject line (can be altered for other cases)
key = re.compile(r'wde load \d{3}') #requires regulars expressions (i.e. 'import re')
for message in ticketMessages:
#will skip any message that does not match the correct subject line format (non-case sensitive)
check = str(message.Subject).lower()
if key.search(check) == None:
continue
attachments = message.Attachments
tic = attachments.item(1)
ticnum = str(message.Subject).split()[2]
name = str(tic).split()[0] + ' ticket ' + ticnum + '.pdf' #changes the filename
tic.SaveAsFile('C:\\Users\\bhalvorson\\Desktop\\Attachments' + os.sep + str(name))
if message.UnRead == True:
message.UnRead = False
message.Move(done)
print('Ticket pdf: ' + name + ' save successfully')
好吧,我找到了我自己问题的答案。我会把它贴在这里,以防其他年轻人遇到和我一样的问题。你知道吗
主要问题是消息。移动(完成)“倒数第二。 显然,move函数改变了当前文件夹,从而改变了for循环将通过的循环数。因此,按照上面写的方式,代码只处理文件夹中的一半项目。你知道吗
一个简单的解决方法是将for循环的主线切换到“for message in list(ticketMessages):”列表不受Move函数的影响,因此您可以循环处理每条消息。你知道吗
希望这对别人有帮助。你知道吗
相关问题 更多 >
编程相关推荐