簡體   English   中英

使用python在Outlook電子郵件中保存附件

[英]Saving attachments in Outlook emails using python

我正在嘗試根據主題和發件人電子郵件掃描我的 Outlook 收件箱,然后嘗試在特定位置本地下載任何附加文件。

此代碼目前永遠運行,而不會檢測到具有所需發件人地址和主題的電子郵件。

import win32com.client
import re

# set up connection to outlook
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetFirst()
while True:
  try:
    current_sender = str(message.Sender).lower()
    current_subject = str(message.Subject).lower()
    if re.search('The Subject I am scanning for',current_subject) != None and re.search('the sender email address to scan for',current_sender) != None:
      print(current_subject) 
      print(current_sender)  
      attachments = message.Attachments
      attachment = attachments.Item(1)
      attachment_name = str(attachment).lower()
      attachment.SaveASFile("Y:"+"\\" +"STRATEGIES"+"\\" + attachment_name)
    else:
      pass
    message = messages.GetNext()
  except:
    message = messages.GetNext()
exit

理想情況下,一旦特定電子郵件的附件下載完成,該電子郵件將被放置在我的存檔文件夾中,該文件夾位於索引 39 中。

首先,不要循環遍歷 fodler 中的所有消息 - 使用Items.FindFirst/FindsNextItems.Restrict

其次, MailItem.Sender是一個對象,而不是一個字符串。 當您將其轉換為字符串時,它會使用默認屬性(即Name )進行轉換。 你想要的是MailItem.SenderEmailAddress

將來,您確實需要單步執行代碼並查看變量的值,看看它們是否符合您的預期。

暫無
暫無

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

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