用于使用imap下载新电子邮件附件的Python脚本

时间:2017-05-10 12:20:10

标签: python outlook

导入电子邮件     导入imaplib     import os

class FetchEmail():

    connection = None
    error = None
    mail_server="outlook.office365.com"
    username="me@domain.com"
    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

我目前有上面的代码,在第12行它说自我没有定义。这可能是造成这种错误的原因。我认为self是在 init 函数中的那一行下面定义的。

1 个答案:

答案 0 :(得分:0)

好吧,只要查看代码,我就可以从一开始就看到不一致的缩进 - 这可能是你的主要问题。尝试在FetchEmail类中定义函数。

其次,将 init 功能更改为:

def __init__(self, mail_server=mail_server, username=username, password=password):

这实际上只是将默认值应用于 init 功能。 最后,对于我们类中的save_attachment函数/ save_attachment(self, msg, download_folder),您需要在 init 函数内或在scipt的顶级函数内调用它(外部)类定义)

  • 在类定义中(在init中):self.save_attatchment(msg,download_folder)
  • 在顶级:使用FetchEmail创建fe = FetchEmail()对象后,您可以像这样调用save_attachment函数:attatchment_path = fe.save_attachment()

这就是我实现 init 的方式:

class FetchEmail():
    def __init__(self,
        mail_server="outlook.office365.com", 
        username="rnandipati@jmawireless.com",
        password="'RNjma17!'"):

        self.error = None
        self.connection = None
        self.mail_server = mail_server
        self.username = username
        self.password = password
        self.connection = imaplib.IMAP4_SSL(mail_server)
        self.connection.login(username, password)
        self.connection.select(readonly=False) # so we can mark mails as readread

    def close_connection(self): ...

请注意,如果您这样做,请记住将所有功能的引用更改为self.passwordself.error等。

我不知道这是否有效。 也许看看this。我认为这是你最好的选择。

一切顺利!