Feb-21-2020, 04:45 AM
As the title, so is my goal. But i am stuck as this code is going into infinite loop with downloading attachments of 1 email only. I'm still trying to get this code work.
Please assist what amendments are needed to make it work & if i can optimize it further.
Please assist what amendments are needed to make it work & if i can optimize it further.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# Date : 20-Dec-2020 # Code version 0.1 import datetime import datetime as dt import os import os.path import win32com.client """ Objective: Read today's all the email from a dedicated folder in outlook. Download the email's attachments in a folder( folder name should be 'email sender + subject + date') on my machine """ os.chdir(r 'C:\Users\vinilm\PycharmProjects\ROTA' ) # print("************Current working Directory : {} ************".format(os.getcwd())) now = dt.datetime.now() suffix = now.strftime( "%d-%m-%y" ) # d = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%d-%m-%y") # Yesterday's date def download_attachment(): global count_attachment outlook = win32com.client.Dispatch( "Outlook.Application" ).GetNamespace( "MAPI" ) inbox = outlook.GetDefaultFolder( 6 ).Folders( "ROTA" ) mail_items = inbox.Items message = mail_items.GetLast() while mail_items: subject, sender, attachment, count_attachment = message.Subject, message.Sender, message.Attachments, \ message.Attachments.Count print ( "Email Sender Name:- {0} \nEmail Subject :- {1} \nNo of attachments : {2}\n" . format (sender, subject, count_attachment)) """ if path exist, ok else create the path/Downloads folder """ new_name = "Mass Request " + str (sender) + str (suffix) if new_name in os.listdir(): pass else : os.mkdir(new_name) path = os.path.join(os.getcwd(), new_name) # date = message.SentOn.strftime("%d-%m-%y") if count_attachment > 0 : for i in range ( 1 , count_attachment + 1 ): attach = attachment.Item(i) attach.SaveAsFile(path + '\\' + str (attach)) else : print ( "No attachment found !" ) exit( 2 ) print ( "From Today's Requests, {0} File(s) downloaded successfully !! " . format (count_attachment)) mail_items.GetPrevious() if __name__ = = "__main__" : download_attachment() |