簡體   English   中英

Python 僅保存電子郵件正文中的附件

[英]Python is saving only the attachments from e-mail body

我正在編寫一個腳本,它將我打開的電子郵件的所有附件發送到特定路徑。 總而言之,我使用的主要代碼如下:

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem('path to .msg i want to open')
attachments = msg.Attachments
        attachment_no = len([x for x in attachments])
        for x in range(1, attachment_no):
            attachment = attachments.Item(x)
            attachment.SaveASFile('path' + str(attachment))

它運作良好,我沒有收到任何錯誤,但不如預期。 腳本不是保存附件,比如 PDF,而是保存嵌入在電子郵件正文中的文件,即圖片、發件人簽名等。 因此,我得到了一些 .jpg 文件,而不是附加的 PDF。

我在這里做錯了什么?

先感謝您!

嘗試

    attachments = msg.Attachments
    for x in range(1, attachments.Count):
        attachment = attachments.Item(x)
        attachment.SaveAsFile('path' + attachment.FileName)

如果您需要區分隱藏附件(嵌入圖像)並僅保存附件,則需要檢查PR_ATTACH_CONTENT_ID屬性值並嘗試在 email 的消息正文中搜索該值。 這是因為附件可能始終具有 MIME 內容 ID 集 ( PR_ATTACH_CONTENT_ID ),例如,來自 Lotus Notes 的消息始終具有 header。 有關詳細信息,請參閱使用 Outlook VBA 區分可見和不可見附件

PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001F"
 
for x in range(1, attachment_no):
      attachment = attachments.Item(x)
      pa = attachment.propertyAccessor
      cid = pa.GetProperty(PR_ATTACH_CONTENT_ID)

      // search the cid value in the message body

      attachment.SaveASFile('path' + attachment.FileName) 
       

設法弄清楚了。

attachments = msg.Attachments
        attachment_no = len([x for x in attachments])
        for x in range(1, attachment_no + 1):
            attachment = attachments.Item(x)
            attachment.SaveASFile('path' + str(attachment))

在附件數量后添加了“+1”。 這是合乎邏輯的,因為從 1 到 3 的范圍意味着只保存附件 1 和 2。 這對我來說是一種誤導,因為如果您在電子郵件中只有一個附件,則只會保存“正文附件”,而不是文件附件本身。 我在想文件根本沒有保存,但實際上只有最后一個附件沒有保存,因為錯誤的“for x in range”行。 因此,為了保存所有附件,范圍內的總數應增加一。

暫無
暫無

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

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