【问题标题】:Saving attachments in Outlook emails using python使用 python 在 Outlook 电子邮件中保存附件
【发布时间】:2021-09-22 16:44:50
【问题描述】:

我正在尝试根据主题和发件人电子邮件扫描我的 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 中。

【问题讨论】:

    标签: python email outlook email-attachments


    【解决方案1】:

    首先,不要遍历文件夹中的所有消息 - 使用 Items.FindFirst/FindsNextItems.Restrict

    其次,MailItem.Sender 是一个对象,而不是一个字符串。当您将其转换为字符串时,它会使用默认属性(即Name)进行转换。你要的是MailItem.SenderEmailAddress

    将来,您确实需要单步执行您的代码并查看变量的值,看看它们是否符合您的预期。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 2015-05-29
      • 2021-06-26
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多