【问题标题】:How to download outlook attachment from Python Script?如何从 Python 脚本下载 Outlook 附件?
【发布时间】:2017-02-01 01:23:36
【问题描述】:

我需要使用 Python 脚本从邮件中下载没有过去附件的传入附件。

例如:如果有人在这个时候(现在)发送邮件,那么只需将该附件下载到本地驱动器而不是过去的附件。

请任何人帮助我使用 python 脚本或 java 下载附件。

【问题讨论】:

  • 看起来你需要一个爬虫,试试 selenium
  • 我已经有 python 代码从 gmail 下载未读附件。但我需要从 Outlook 邮件下载附件。

标签: python email outlook


【解决方案1】:

下面的代码有助于从 Outlook 电子邮件中下载附件

  • 未读”(并将邮件更改为已读。)或从“今天”日期开始。
  • 不改变文件名。

只需传递 'Subject' 参数。

import datetime
import os
import win32com.client


path = os.path.expanduser("~/Desktop/Attachments")
today = datetime.date.today()

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) 
messages = inbox.Items


def saveattachemnts(subject):
    for message in messages:
        if message.Subject == subject and message.Unread or message.Senton.date() == today:
            # body_content = message.body
            attachments = message.Attachments
            attachment = attachments.Item(1)
            for attachment in message.Attachments:
                attachment.SaveAsFile(os.path.join(path, str(attachment)))
                if message.Subject == subject and message.Unread:
                    message.Unread = False
                break

【讨论】:

  • 运行此代码我得到一个“底层安全系统找不到您的数字 ID 名称。”错误 - 这似乎与加密有关。你知道有没有办法解决这个问题?就像只从未加密的电子邮件中提取附件,或者以某种方式将您的公钥添加到 win32?
  • 使用你的代码,给我错误com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Array index out of bounds.', None, 0, -2147352567), None)
  • 如何让它从一封电子邮件中下载多个附件?
  • 要保存多个附件,请删除最后一个 break 语句。消息对象的 Senton 属性出错。似乎这个可能已更改为 SentOn:docs.microsoft.com/en-us/office/vba/api/outlook.mailitem.senton。否则代码就像一个魅力。
【解决方案2】:
import win32com.client #pip install pypiwin32 to work with windows operating sysytm
import datetime
import os

# To get today's date in 'day-month-year' format(01-12-2017).
dateToday=datetime.datetime.today()
FormatedDate=('{:02d}'.format(dateToday.day)+'-'+'{:02d}'.format(dateToday.month)+'-'+'{:04d}'.format(dateToday.year))

# Creating an object for the outlook application.
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
# Creating an object to access Inbox of the outlook.
inbox=outlook.GetDefaultFolder(6)
# Creating an object to access items inside the inbox of outlook.
messages=inbox.Items

def save_attachments(subject,which_item,file_name):
    # To iterate through inbox emails using inbox.Items object.
    for message in messages:
        if (message.Subject == subject):
            body_content = message.body
            # Creating an object for the message.Attachments.
            attachment = message.Attachments
            # To check which item is selected among the attacments.
            print (message.Attachments.Item(which_item))
            # To iterate through email items using message.Attachments object.
            for attachment in message.Attachments:
                # To save the perticular attachment at the desired location in your hard disk.
                attachment.SaveAsFile(os.path.join("D:\Script\Monitoring",file_name))
                break

【讨论】:

  • 运行此代码我得到一个“底层安全系统找不到您的数字 ID 名称。”错误 - 这似乎与加密有关。你知道有没有办法解决这个问题?就像只从未加密的电子邮件中提取附件,或者以某种方式将您的公钥添加到 win32? (理解错误来源:knowledge.digicert.com/solution/SO4972.html
【解决方案3】:

当我复制这段代码时,我得到一个错误:

连接 = 无 ^ IndentationError: 需要一个缩进块

然后,当我缩进代码时,

class FetchEmail():
    connection = None
    error = None
    mail_server = "imap.gmail.com"
    username = "dummyoffers@gmail.com"
    password = "opennepo"
    self.save_attachment(self, msg, download_folder)

我收到另一个错误:

self.save_attachment(self, msg, download_folder) NameError: name 'self' 没有定义

import email
import imaplib
import os

class FetchEmail():

connection = None
error = None
mail_server="host_name"
username="outlook_username"
password="password"
self.save_attachment(self,msg,download_folder)
def __init__(self, mail_server, username, password):
    self.connection = imaplib.IMAP4_SSL(mail_server)
    self.connection.login(username, password)
    self.connection.select(readonly=False) # so we can mark mails as read

def close_connection(self):
    """
    Close the connection to the IMAP server
    """
    self.connection.close()

def save_attachment(self, msg, download_folder="/tmp"):
    """
    Given a message, save its attachments to the specified
    download folder (default is /tmp)

    return: file path to attachment
    """
    att_path = "No attachment found."
    for part in msg.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue

        filename = part.get_filename()
        att_path = os.path.join(download_folder, filename)

        if not os.path.isfile(att_path):
            fp = open(att_path, 'wb')
            fp.write(part.get_payload(decode=True))
            fp.close()
    return att_path

def fetch_unread_messages(self):
    """
    Retrieve unread messages
    """
    emails = []
    (result, messages) = self.connection.search(None, 'UnSeen')
    if result == "OK":
        for message in messages[0].split(' '):
            try: 
                ret, data = self.connection.fetch(message,'(RFC822)')
            except:
                print "No new emails to read."
                self.close_connection()
                exit()

            msg = email.message_from_string(data[0][1])
            if isinstance(msg, str) == False:
                emails.append(msg)
            response, data = self.connection.store(message, '+FLAGS','\\Seen')

        return emails

    self.error = "Failed to retreive emails."
    return emails

以上代码适用于我下载附件。希望这对任何人都有帮助。

【讨论】:

  • 你知道如何让它适用于公司电子邮件吗?喜欢 yourname@company.com?这对于基本的 Outlook 或 gmail 帐户非常有效,但我无法弄清楚 电子邮件。
  • 希望它也适用于公司电子邮件。如果您遇到任何问题,请尝试使用您的公司帐户并写信给我。
  • @MahendraPrabhu 请帮忙,我遇到同样的缩进错误
【解决方案4】:

如果您想从特定发件人的 Outlook 应用程序中下载带有特定主题的附件。下面的代码可能会有所帮助。

import win32com.client
import os
from datetime import datetime, timedelta
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
for account in mapi.Accounts:
    print(account.DeliveryStore.DisplayName) #outlook account
inbox = mapi.GetDefaultFolder(6) #Inbox folder
inbox = inbox.Folders["your folder"] #Folder inside Inbox Folder
messages = inbox.Items 
received_dt = datetime.now() - timedelta(days=1)
received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p')
email_sender = 'sender@outlook.com'
email_subject = 'Subject of mail'
messages = messages.Restrict("[ReceivedTime] >= '"+received_dt+"'")
#save to current directory
outputDir = os.getcwd()
try:
    for message in list(messages):
        if email_subject == message.subject and message.SenderEmailAddress == email_sender and message.ReceivedTime.strftime('%Y-%m-%d') == _date:
            try:
                s = message.sender
                for attachment in message.Attachments:
                    attachment.SaveASFile(os.path.join(outputDir, attachment.FileName))
                    print(f"attachment {attachment.FileName} from {s} saved"
            except Exception as e:
                print("Error when saving the attachment:" + str(e))
except Exception as e:
    print("Error when processing emails messages:" + str(e))

【讨论】:

  • 您好,您的代码出现缩进问题和不需要的return语句,请修复它以便其他人可以使用它。发布之前请检查语法错误。
  • 嗨@Abhishek,我已经做了必要的更改。谢谢你告诉我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多