如何从 Python 脚本下载 Outlook 附件? [英] How to download outlook attachment from Python Script?

查看:38
本文介绍了如何从 Python 脚本下载 Outlook 附件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to download incoming attachment without past attachment from mail using Python Script.

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

For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments.

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

Please anyone help me to download attachment using python script or java.

推荐答案

当我复制此代码时,出现错误:

When I copied this code, I get an error:

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

connection = None ^ IndentationError: expected an indented block

然后,当我缩进代码时,

and then, when I indent the code,

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' 未定义

self.save_attachment(self, msg, download_folder) NameError: name 'self' is not defined

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

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

Above code works for me to download attachment.Hope this really helpful for any one.

这篇关于如何从 Python 脚本下载 Outlook 附件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆