【问题标题】:getting specific xlsx attachment from outlook and saving it on my windows computer从 Outlook 获取特定的 xlsx 附件并将其保存在我的 Windows 计算机上
【发布时间】:2021-07-20 21:19:07
【问题描述】:

希望你一切都好。

我一直在用网络抓取进行一些 python 练习,并且遇到了 win32com 库,并且一直在努力从我的 Outlook 电子邮件中获取附件(它只是一个)!我设法通过以下代码查看了所有电子邮件。我想知道您是否可以帮助我获取名为“data_bay1.xlsx”的附件文件,因为我对错误感到困惑。到目前为止,我可以从电子邮件中获取数据,但是当我尝试运行它时,我无法获取附件 xlsx 文件和代码的附件部分,它给了我错误。请看看我到目前为止做了什么,我希望你们中的任何人都可以提供帮助。我正在使用 anaconda 和 windows。先感谢您!亲切的问候,莉莉

   import win32com.client
   
#connecting python to outlook

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
 
#connecting to our inbox

inbox = outlook.GetDefaultFolder(6)
(inbox)

# here we are ensuring the indexes exist so we can grab data

outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
for i in range(50):
 try:
   box = outlook.GetDefaultFolder(i)
   name = box.Name
   print(i, name)
 except:
   pass

messages = inbox.items

messages = messages.GetFirst() earlier
# get the last email
#message = messages.GetLast()
(message)

#to loop through the email in the inbox 

while True:
 try:
   print(message.subject) # get the subject of the email
   # if you use messages.GetFirst() earlier
   message = messages.GetNext() 
   # if you use messages.GetPrevious() earlier 
   #message = messages.GetPrevious()
 except:
   # if you use messages.GetFirst() earlier
   message = messages.GetNext() 
   # if you use messages.GetPrevious() earlier 
   #message = messages.GetPrevious()



# get the attachment

 attachments = message.Attachments# return the first item in attachments
 attachment = attachments.Item(1)
 # the name of attachment file      
 attachment_name = str(attachment).lower()
 attachment.SaveASFile(path+ 'C:\Users\lily\OneDrive - Dataenv\Documents + attachment_data_bay1)


 
 

【问题讨论】:

    标签: python outlook xlsx win32com


    【解决方案1】:

    遍历文件夹中的所有项目并不是一个好主意:

    #to loop through the email in the inbox 
    
    while True:
     try:
       print(message.subject) # get the subject of the email
       # if you use messages.GetFirst() earlier
       message = messages.GetNext() 
       # if you use messages.GetPrevious() earlier 
       #message = messages.GetPrevious()
     except:
       # if you use messages.GetFirst() earlier
       message = messages.GetNext() 
       # if you use messages.GetPrevious() earlier 
       #message = messages.GetPrevious()
    

    相反,您需要使用ItemsFind/FindNextRestrict 方法来查找与您的条件相对应的项目。在以下文章中详细了解这些方法:

    您可以做的最好的事情是将列表过滤到仅包含附件的项目。为此,请使用 PR_HASATTACHDASL 名称为 http://schemas.microsoft.com/mapi/proptag/0x0E1B000B)MAPI 属性,然后遍历返回的项目并处理其附件集合。

    【讨论】:

      猜你喜欢
      • 2022-12-14
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2021-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多