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.
# 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()