簡體   English   中英

如何閱讀在 Outlook 中收到的 Excel 電子郵件附件?

[英]How to read in Excel email attachments received in Outlook?

所以我試圖從 Microsoft Outlook 的附件中讀取 Excel 文件。 下面的代碼有效,但僅當我嘗試從中讀取附件的電子郵件位於收件箱頂部時。 如何調整我的代碼,以便它查看我的收件箱文件夾中的所有電子郵件,查找附件或根據提供的主題查找電子郵件。 此外,我最終希望使用共享郵箱進行這項工作,但現在這是次要問題。

from win32com.client import Dispatch
import email
import datetime as date
import os

outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = date.date.today()

sub_today = 'subject of email'
att_today = 'Filename'


for msg in all_inbox:
    yourstring = msg.Subject.encode('ascii', 'ignore').decode('ascii')
    if(yourstring.find('"Filename"') != -1):
        break


for att in msg.Attachments:
    if att.FileName == att_today:
        attachments = msg.Attachments
        break

attachment = attachments.Item(1)
fn = os.getcwd() + '\\' + att_today
attachment.SaveASFILE(fn)
df = pd.read_excel(fn)

首先,要遍歷所有需要跳過的項目,而不是打破循環。 在循環中使用continue關鍵字而不是break

Outlook 對象模型提供Find / FindNextRestrict方法來獲取與您的條件相對應的項目。 商店提供者的工作比僅僅遍歷文件夾中的所有項目更有效。 在以下文章中閱讀有關這些方法的更多信息:

您可以使用以下搜索條件,其中查詢對消息主題中的hello執行短語匹配查詢(VBA 語法):

filter = "@SQL=" & Chr(34) & "https://schemas.microsoft.com/mapi/proptag/0x0037001E" _
    & Chr(34) & " ci_phrasematch " & "'hello'"

使用NameSpace.GetSharedDefaultFolder方法獲取共享文件夾,該方法返回一個Folder對象,該對象代表指定用戶的指定默認文件夾。 此方法用於委派方案,其中一個用戶已將一個或多個默認文件夾(例如,他們的共享Calendar文件夾)的訪問權限委派給另一個用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM