Loop Through Outlook Emails with Python

How to Loop Through Outlook Emails with Python

Use pywin32 to loop through Outlook emails in specific folders or by subject line

**This Python Outlook Automation will only work on Windows PC Devices and Microsoft Outlook email client**

This article will teach you how to loop through Outlook emails (or iterate through Outlook emails) using Python. Looping through Outlook emails is one of the most important features when you are trying to automate any Outlook task. We will show you how you can loop through emails in your Inbox, a specific Outlook folder, or even just based on the subject line. Please note, this code only focuses on looping through emails in one folder at a time.

Once you learn how to iterate through Outlook emails, it will be much easier to perform other Outlook automation tasks, like learning how to automatically download Outlook attachments or how to parse the body of an email for a specific word or number. Below we will go through several ways to loop through Outlook emails using Python, and print out the sender, subject line, and time received.

First, import the win32com.client and os packages.

import win32com.client
import os

#having issues installing win32com? try the below (without the hashtag)

#pip install pypiwin32
#pip install pywin32
#python -m pip install pypiwin32

How To Loop Through Outlook Emails in Inbox with pywin32

import win32com.client
import os

#Define your variables
num_emails_limit = 10 #loops through last 10 emails in folder
folder_name = 'Inbox' #name of Outlook folder you want to search

#Opens Outlook application
outlook_application = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
outlook_mailbox =outlook_application.Folders.Item(1)

#Finds the correct Outlook Folder by searching for a folder that is equal to folder_name
for folder in outlook_mailbox.Folders:
    if folder.Name == folder_name:
        found_folder = folder
        print('Folder Searched:' + found_folder.Name)

#Sorts all emails in folder by date (descending)
folder_emails = found_folder.Items
folder_emails.Sort("[ReceivedTime]", True)

#Loops Through Outlook Emails
counter = 0
for email in folder_emails:
    try:
        email_num = str(counter+1) 
        email_sender = str(email.Sender)
        email_subject = str(email.Subject)
        email_recieved_date = str(email.ReceivedTime.strftime('%m-%d-%y'))
        print('Email ' + email_num + ' Sender: ' + email_sender + ' | Subject: ' + email_subject   + ' | Date Received: ' + email_recieved_date)
        counter = counter +1
    except:
        print('Calendar Invite Skipped')
        pass
    if counter == num_emails_limit:
        break

OUTPUT: How To Loop Through Outlook Emails in Inbox with pywin32

Folder Searched: Inbox
Email 1 Sender: Ashely| Subject: RE: test | Date Received: 11-12-22
Email 2 Sender: Bob| Subject: test | Date Received: 11-12-22
Email 3 Sender: Frances| Subject: [EXTERNAL] Security alert| Date Received: 11-12-22
Email 4 Sender: Jake| Subject:  Release Update: November 11th 2022 | Date Received: 11-12-22
Email 5 Sender: Kevin| Subject: [EXTERNAL] A Holiday Tradition | Date Received: 11-11-22
6. Calendar Invite Skipped 
Email 7 Sender: Maria| Subject: Re: Entertainment| Date Received: 11-11-22
Email 8 Sender: Gisele| Subject: RE: Entertainment| Date Received: 11-11-22
Email 9 Sender: Camila| Subject: [EXTERNAL] Support Ticket Update | Date Received: 11-11-22
Email 10 Sender: Katie| Subject: Re: Entertainment| Date Received: 11-11-22

The above Python function was written by our team to ensure you have everything you need to loop through your Outlook Inbox. The only variable you need to define here is num_emails_limit. This is how many emails you want to search for, the code above is currently set to look at the last 10 emails in your Inbox. It also skips over calendar invites. The output above shows what the code will produce after sucessfully running.

How To Loop Through Outlook Emails in a Specific Folder with pywin32

Need a different folder other than your Inbox? The code is actually the exact same as above, you just edit folder_name from ‘Inbox’ to the exact name of your folder!

import win32com.client
import os

#Define your variables
num_emails_limit = 10 #loops through last 10 emails in folder
folder_name = 'FOLDER_NAME_HERE' #name of Outlook folder you want to search

#Opens Outlook application
outlook_application = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
outlook_mailbox =outlook_application.Folders.Item(1)

#Finds the correct Outlook Folder by searching for a folder that is equal to folder_name
for folder in outlook_mailbox.Folders:
    if folder.Name == folder_name:
        found_folder = folder
        print('Folder Searched:' + found_folder.Name)

#Sorts all emails in folder by date (descending)
folder_emails = found_folder.Items
folder_emails.Sort("[ReceivedTime]", True)

#Loops Through Outlook Emails
counter = 0
for email in folder_emails:
    try:
        email_num = str(counter+1) 
        email_sender = str(email.Sender)
        email_subject = str(email.Subject)
        email_recieved_date = str(email.ReceivedTime.strftime('%m-%d-%y'))
        print('Email ' + email_num + ' Sender: ' + email_sender + ' | Subject: ' + email_subject   + ' | Date Received: ' + email_recieved_date)
        counter = counter +1
    except:
        print('Calendar Invite Skipped')
        pass
    if counter == num_emails_limit:
        break

OUTPUT: How To Loop Through Outlook Emails in A Specific Folder with pywin32

Folder Searched:Monthly Report
Email 1 Sender: Reporting Company | Subject: [EXTERNAL] Monthly Report | Date Received: 11-03-22
Email 2 Sender: Reporting Company | Subject: [EXTERNAL] Monthly Report  | Date Received: 11-03-22
Email 3 Sender: Reporting Company | Subject: [EXTERNAL] Monthly Report  | Date Received: 10-03-22
Email 4 Sender: Reporting Company | Subject: [EXTERNAL] Monthly Report | Date Received: 10-03-22
Email 5 Sender: Reporting Company | Subject: [EXTERNAL] Monthly Report  | Date Received: 09-03-22
Email 6 Sender: Reporting Company | Subject: [EXTERNAL] Monthly Report | Date Received: 09-03-22
Email 7 Sender: Reporting Company | Subject: [EXTERNAL] Monthly Report | Date Received: 08-03-22
Email 8 Sender: Reporting Company | Subject: [EXTERNAL] Monthly Report  | Date Received: 08-03-22
Email 9 Sender: Reporting Company | Subject: [EXTERNAL] Monthly Report | Date Received: 07-03-22
Email 10 Sender: Reporting Company | Subject: [EXTERNAL] Monthly Report  | Date Received: 07-03-22

How To Loop Through Outlook Emails by Subject Line

import win32com.client
import os

#Define your variables
num_emails_limit = 10 #loops through last 10 emails in folder
folder_name = 'Inbox' #name of Outlook folder you want to search
subject_line = 'RE:' #Gets last 10 emails that contain "RE:" in the subject line"

#Opens Outlook application
outlook_application = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
outlook_mailbox =outlook_application.Folders.Item(1)

#Finds the correct Outlook Folder by searching for a folder that is equal to folder_name
for folder in outlook_mailbox.Folders:
    if folder.Name == folder_name:
        found_folder = folder
        print('Folder Searched:' + found_folder.Name)

#Sorts all emails in folder by date (descending)
folder_emails = found_folder.Items
folder_emails.Sort("[ReceivedTime]", True)

#Loops Through Outlook Emails
counter = 0
for email in folder_emails:
    try:
        if subject_line in email.Subject: #If exact subject_line match is needed, switch "in" to "=="
                email_num = str(counter+1) 
                email_sender = str(email.Sender)
                email_subject = str(email.Subject)
                email_recieved_date = str(email.ReceivedTime.strftime('%m-%d-%y'))
                print('Email ' + email_num + ' Sender: ' + email_sender + ' | Subject: ' + email_subject   + ' | Date Received: ' + email_recieved_date)
                counter = counter +1
    except:
        print('Calendar Invite Skipped')
        pass
    if counter == num_emails_limit:
        break

Now, the code for looping through outlook emails with subject line is a little different than iterating emails through your inbox or a specific folder. This is because we have to add one additional if statement that checks if the email’s subject line matches the variable subject_line we define in the beginning of the code. This code can be useful if you want to see all the replies in your Inbox from a certain thread, or find all emails containing a certain Monthly report. Please note the above code is using a “contains” for subject line. Simply switch the “in” to a double equals “==” where the code is notated in order to get an exact match.

OUTPUT: Loop Through Outlook Emails in Inbox by Subject Line

Folder Searched: Inbox
Email 1 Sender: Ashely|RE: test| Date Received: 11-12-22
Email 2 Sender: Bob|RE: Entertainment OS| Date Received: 11-12-22
Email 3 Sender: Frances|RE: MBA Class Help| Date Received: 11-12-22
Email 4 Sender: Jake|RE: Time zone Question| Date Received: 11-12-22
Email 5 Sender: John|RE: Time zone Question| Date Received: 11-11-22
Email 6 Sender: Kevin|RE: Time zone Question| Date Received: 11-11-22
Email 7 Sender: Maria|RE: Master Data Asset| Date Received: 11-11-22
Email 8 Sender: Gisele|RE: Time zone Question| Date Received: 11-11-22
Email 9 Sender: Camila|RE: Time zone Question| Date Received: 11-11-22
Email 10 Sender: Katie|RE: Time zone Question| Date Received: 11-11-22

Full Code: How To Loop Through Outlook Emails in Inbox , Specific Folder, or by Subject Line with pywin32

import win32com.client
import os

#Define your variables
num_emails_limit = 10 #loops through last 10 emails in folder
folder_name = 'Inbox' #name of Outlook folder you want to search
subject_line = 'RE:' #Gets last 10 emails that contain "RE:" in the subject line"

#Opens Outlook application
outlook_application = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
outlook_mailbox =outlook_application.Folders.Item(1)

#Finds the correct Outlook Folder by searching for a folder that is equal to folder_name
for folder in outlook_mailbox.Folders:
    if folder.Name == folder_name:
        found_folder = folder
        print('Folder Searched:' + found_folder.Name)

#Sorts all emails in folder by date (descending)
folder_emails = found_folder.Items
folder_emails.Sort("[ReceivedTime]", True)

#Loops Through Outlook Emails
counter = 0
for email in folder_emails:
    try:
        if subject_line in email.Subject: #If exact subject_line match is needed, switch "in" to "=="
                email_num = str(counter+1) 
                email_sender = str(email.Sender)
                email_subject = str(email.Subject)
                email_recieved_date = str(email.ReceivedTime.strftime('%m-%d-%y'))
                print('Email ' + email_num + ' Sender: ' + email_sender + ' | Subject: ' + email_subject   + ' | Date Received: ' + email_recieved_date)
                counter = counter +1
    except:
        print('Calendar Invite Skipped')
        pass
    if counter == num_emails_limit:
        break

Congratulations! You now know a fundamental skill for Python Outlook Automation tasks : iterating through Outlook emails in the Inbox, a specific folder, or by subject line. We hope this code helps you automate your workflow and helps you take on your next project with confidence. What will YOU do with your extra time automating Outlook tasks with Python will save?


Comments

11 responses to “How to Loop Through Outlook Emails with Python”

  1. […] to access something other than the last email? Check out How to Loop Through Outlook Emails with Python […]

  2. […] to access something other than the last email? Check out How to Loop Through Outlook Emails with Python […]

  3. I absolutely agree with you. The idea is great, I support it.

  4. It’s wondderful that youu aare getting thougghts from thjs post aas well aas frm our discusssion made aat this time.

  5. Not at all. I know.

  6. I apologize for interfering … But this topic is very close to me. I can help with the answer.

  7. Nice post! You have written useful and practical information. Take a look at my web blog Webemail24 I’m sure you’ll find supplementry information about Tantric Massage you can gain new insights from.

  8. You’ve written terrific content on this topic, which goes to show how knowledgable you are on this subject. I happen to cover about SEO on my personal blog Seoranko and would appreciate some feedback. Thank you and keep posting good stuff!

  9. Your ideas absolutely shows this site could easily be one of the bests in its niche. Drop by my website Articleworld for some fresh takes about Piping Systems. Also, I look forward to your new updates.

  10. This is some awesome thinking. Would you be interested to learn more? Come to see my website at 85N for content about Webdesign.

Leave a Reply

Your email address will not be published. Required fields are marked *