我不允许我使用pywin32保存电子邮件附件

时间:2017-08-01 15:54:03

标签: python email outlook pywin32

import win32com.client
import pythoncom
import time
import os

class Handler_Class(object):
    def OnNewMailEx(self, receivedItemsIDs):
        # RecrivedItemIDs is a collection of mail IDs separated by a ",".
        # You know, sometimes more than 1 mail is received at the same moment.

        for ID in receivedItemsIDs.split(","):
            print('Running scan...')
            mail = outlook.Session.GetItemFromID(ID)
            email_date = mail.SentOn.strftime("%m-%d-%y" + " at " + "%I:%M:%S %p")
            email_date_stamp = mail.SentOn.strftime('%m-%d-%y_%I:%M:%S-%p')
            email_message = mail.Body
            email_subject = mail.Subject
            email_sender = mail.SenderEmailAddress
            email_attachments = mail.Attachments

            try:

                if check_correct_subject(email_subject) == True:
                        print('From: ' + email_sender)
                        print('Subject: ' + email_subject)
                        print('Date: ' + email_date)

                        if email_attachments.Count > 0:
                            print(str(email_attachments.Count) + ' attachments found.')
                            for i in range(email_attachments.Count):
                                email_attachment = email_attachments.Item(i + 1)

                                report_name = email_date_stamp + '_' + email_attachment.FileName
                                print(report_name)
                                email_attachment.SaveASFile(os.getcwd() + '\\Reports\\Broker_Risk_LDW\\' + report_name)

                                print('Pushing attachment - ' + report_name + ' - to check_correct_email() function.')

                                if check_correct_attachment(email_attachment) == True:
                                    save_incoming_report(email_attachment, report_name, get_report_directory(email_subject))

                                else:
                                    print('Not the attachment we are looking for.')
                                    # add error logging here
                                    break

                        else:  # ***********add error logging here**************
                            print('No attachment found.')


            except:
                pass

我这样叫这个班。

if __name__ == '__main__':
    outlook = win32com.client.DispatchWithEvents("Outlook.Application", Handler_Class)

#and then an infinit loop that waits from events.
    pythoncom.PumpMessages()

这里的问题是这一行:email_attachment.SaveASFile(os.getcwd() + '\\Reports\\Broker_Risk_LDW\\' + report_name)

该文件夹已经创建,并且在我将其切换到类之前它正在工作,以便使用Outlook事件侦听器。我没有收到错误消息,但附件未保存。

任何提示?

0 个答案:

没有答案