Python Forum
Help Needed | Read Outlook email Recursively & download attachment - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help Needed | Read Outlook email Recursively & download attachment (/thread-24590.html)



Help Needed | Read Outlook email Recursively & download attachment - Vinci141 - Feb-21-2020

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



RE: Help Needed | Read Outlook email Recursively & download attachment - cubangt - Jan-07-2022

Not sure if this would help, but if you are expecting to only search for a certain number of emails, why not get the "count" of emails found to download and loop thru that number of emails, so that once its processed all x emails, it stops looping?

What is being returned in this variable?
mail_items

You have to be able to tell the logic that it needs to stop, you could technically create a Boolean variable outside the while, set it to false
Then after line 60 mail_items.GetPrevious() set that to true.

Then wrap your while with if false, run logic..

Just an idea.