Arpit jain
Arpit jain

Reputation: 99

Want to fetch outlook mails from the oldest mail to the newest mail using python

What I'm doing here is fetching emails from outlook using python. The problem is its getting random emails while fetching. What I want is to fetch emails in a sorted manner from the oldest to the newest emails so that I can store it to any database in a well-structured form(more helpful if any logic that will extract datewise from the oldest to the newest in one loop.). Any help will be appreciated.

def emailleri_al(folder):
    messages = folder.Items  ## want to add logic here
    for message2 in messages:
        Subject=message2.Subject
        print(Subject)        
for account in accounts:
    if account.DisplayName=="[email protected]":

        global inbox
        inbox = outlook.Folders(account.DeliveryStore.DisplayName)

        folders = inbox.Folders

        for f in folders:
            emailleri_al(f)

print("Finished Successfully")

Upvotes: 0

Views: 997

Answers (3)

Somdeb Mukherjee
Somdeb Mukherjee

Reputation: 178

I worked on a similar requirement: I needed to list all email with a specific subject in the order they were received - then later pick the latest one. I used a python library called exchangelib.

Here is the python snippet to do it:

for item in account.inbox.all().order_by('-datetime_received')[:100]: #for your requirement you just need to remove [:100] print(item.subject, item.sender, item.datetime_received)

and here is the full code with step by step explanation.

https://medium.com/@theamazingexposure/accessing-shared-mailbox-using-exchangelib-python-f020e71a96ab

Upvotes: 0

Eugene Astafiev
Eugene Astafiev

Reputation: 49395

Iterating over all items in the folder is not really a good idea in Outlook. Instead, I'd suggest extract items in chunks by using the Find/FindNext or Restrict methods of the Items class. You can read more about these methods in the following series of articles:

The Restrict method is an alternative to using the Find method or FindNext method to iterate over specific items within a collection. The Find or FindNext methods are faster than filtering if there are a small number of items. The Restrict method is significantly faster if there is a large number of items in the collection, especially if only a few items in a large collection are expected to be found.

For example, a sample code listed in C# shows to use the Restrict method:

private void RestrictCalendarItems(Outlook.MAPIFolder folder)
{
    DateTime dtEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                                  DateTime.Now.Day, 23, 59, 00, 00);
    string restrictCriteria = "[Start]<=\"" + dtEnd.ToString("g") + "\"" +
                              " AND [End]>=\"" + DateTime.Now.ToString("g") + "\"";
    StringBuilder strBuilder = null;
    Outlook.Items folderItems = null;
    Outlook.Items resultItems = null;
    Outlook._AppointmentItem appItem = null;
    int counter = default(int);
    object item = null;
    try
    {
        strBuilder = new StringBuilder();
        folderItems = folder.Items;
        folderItems.IncludeRecurrences = true;
        folderItems.Sort("[Start]");
        resultItems = folderItems.Restrict(restrictCriteria);
        item = resultItems.GetFirst();
        do
        {
           if (item != null)
           {
               if (item is Outlook._AppointmentItem)
               {
                   counter++;
                   appItem = item as Outlook._AppointmentItem;
                   strBuilder.AppendLine("#" + counter.ToString() +
                                         "\tStart: " + appItem.Start.ToString() +
                                         "\tSubject: " + appItem.Subject +
                                         "\tLocation: " + appItem.Location);
               }
               Marshal.ReleaseComObject(item);
               item = resultItems.GetNext();
           }
       }
       while (item != null);
       if (strBuilder.Length > 0)
           Debug.WriteLine(strBuilder.ToString());
       else
           Debug.WriteLine("There is no match in the "
                            + folder.Name + " folder.");
   }
   catch (Exception ex)
   {
       System.Windows.Forms.MessageBox.Show(ex.Message);
   }
   finally
   {
       if (folderItems != null) Marshal.ReleaseComObject(folderItems);
       if (resultItems != null) Marshal.ReleaseComObject(resultItems);
   }
}

So, you can process ordered items for a small timeslot.

Upvotes: 0

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66215

Call messages.Sort("[ReceivedTime]", false) - see https://learn.microsoft.com/en-us/office/vba/api/outlook.items.sort

Upvotes: 1

Related Questions