繁体   English   中英

使用win32com通过outlook和python下载附件

[英]Using win32com to download attachments through outlook with python

我编写了一个简短的代码来从我的 outlook 帐户中的特定文件夹下载和重命名文件。 该代码运行良好,唯一的问题是我通常需要多次运行代码才能实际下载所有消息。 似乎代码只是未能确认某些消息,当我运行它时没有错误。 我尝试了一些方法,例如在 python window 中逐步遍历每一行,使用 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')

好吧,我找到了自己问题的答案。 我会把它贴在这里,以防其他年轻人遇到和我一样的问题。

主要问题是倒数第二个“message.Move(done)”。 显然,移动 function 改变了当前文件夹,从而改变了 for 循环将 go 通过的循环数。 因此,按照上面的编写方式,代码只处理文件夹中的一半项目。

一个简单的解决方法是将 for 循环的主线切换为“for message in list(ticketMessages):”该列表不受 Move function 的影响,因此您将能够遍历每条消息。

希望这可以帮助某人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM