Python Forum
Help Needed | Read Outlook email Recursively & download attachment
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help Needed | Read Outlook email Recursively & download attachment
#1
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()
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Modifying a dictionary recursively SpongeB0B 2 300 May-12-2024, 04:09 PM
Last Post: Gribouillis
  Unable to download TLS Report attachment blason16 6 694 Feb-26-2024, 07:36 AM
Last Post: Pedroski55
  Extract PDF Attachment from Gmail jstaffon 0 639 Sep-10-2023, 01:55 PM
Last Post: jstaffon
  Search Outlook Inbox for set of values cubangt 1 1,269 Jun-28-2023, 09:29 PM
Last Post: cubangt
  Save image from outlook email cubangt 1 802 Jun-07-2023, 06:52 PM
Last Post: cubangt
  Read All Emails from Outlook and add the word counts to a DataFrame sanaman_2000 0 1,957 Sep-15-2022, 07:32 AM
Last Post: sanaman_2000
  How to return the next page from json recursively? sandson 0 1,234 Apr-01-2022, 11:01 PM
Last Post: sandson
  I get attachment paperclip on email without any attachments monika_v 5 2,154 Mar-19-2022, 10:20 PM
Last Post: cosmarchy
  Mark outlook emails as read using Python! shane88 2 6,787 Feb-24-2022, 11:19 PM
Last Post: Pedroski55
  Trying to determine attachment file type before saving off.. cubangt 1 2,281 Feb-23-2022, 07:45 PM
Last Post: cubangt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020