Code to read an outlook email from Inbox or from Shared Drive and SharePoint


I just installed python 2.7 and have never coded in python. My coding experience dates back many years ago with basic SQL and some basic VBA, korn shell , perl scripting so please forgive my programming ignorance.

I have very specific needs to automate a current heavily manual process which takes time and is prone to error.

I would like to code to read from an input file such as an msg file in an outlook inbox/folder in inbox, and search by the keyword “Approve”, Approved", “approve”, “approved” in the email body and specific description in the subject example “Please approve”. I would like the code to convert the msg into pdf and save in a specific folder on shared drive or share point.

A plus if the code can also retain attachments such as pptx, xlsx within the email after converting msg to pdf and save to the shared drive and share point folder. If this feature is not available, then have the code look for attachments and save in shared drive or share point.

I got the below code written in python 3 from another VBA community user group, was unable to execute and got a syntax error.

I tried taking out “f” from 4 places below as I heard its not compatible with 2? I get the message “returned exit code No process choice made, choose between”. So looks like the code flow stops at below within the main function. I looked up an online book but am unable to find help. Thanks so much for your help, appreciate it!!!

Best Regards,

if (not b_olatt and not b_olbody):
sys.exit(‘No process choice made, choose between ol attachments saver (–olatt) and ol mail body saver (–olbody)!’)

When I run the code,

import sys
import os
import argparse
import csv
import win32com.client

def _right(s, amount):
return s[-amount:]

def _scriptOutput(s, gui_entry):
if gui_entry:
return s

def run_ol_Script(outdest, filefmt, olreadfolder, olprocessedfolder, gui_entry, proc):
outdest = os.path.normpath(outdest)
outlook = win32com.client.Dispatch(“Outlook.Application”).GetNamespace(“MAPI”)
inbox = None
for folder in outlook.Folders:
inbox = folder.Folders[‘Inbox’].Folders[olreadfolder]
except Exception as e:
if inbox is None:
sys.exit(f’No Folder {olreadfolder} found!!! Exiting.’)
procbox = olprocessedfolder
if procbox is not None:
procbox = None
for folder in outlook.Folders:
procbox = folder.Folders[‘Inbox’].Folders[olreadfolder].Folders[olprocessedfolder]
except Exception as e:
if procbox is None:
sys.exit(f’Folder {olprocessedfolder} not found!!! Exiting.’)

messages = inbox.Items
if len(messages) == 0:
    _scriptOutput( 'No emails found in folder [{}]'.format(olreadfolder), gui_entry)

mail_counter = 0
for msg in list(messages):
    b_processed = False
    if proc == 'olatt':
        for atmt in msg.Attachments:
            if filefmt == 'blank' or str.lower(_right(atmt.FileName, len(filefmt))) == str.lower(filefmt):
                temp_filename = os.path.normpath(os.path.join(outdest, f'{msg.Subject} {atmt.FileName}'))
                    print('File Successfully Saved [{}]'.format(temp_filename))
                    b_processed = True
                except Exception as e:
                    _scriptOutput(str(e) + ' | File NOT saved [{}]'.format(temp_filename), gui_entry)
    if proc == 'olbody':
        listbody = msg.Body.split("\r\n")
        temp_filename = os.path.normpath(os.path.join(outdest, f'{msg.Subject} {msg.CreationTime.strftime("%Y%m%d")} .csv'))
        b_processed = True
        with open(temp_filename, 'w', newline='') as file:
            writer = csv.writer(file)
            for row in listbody:
    if b_processed and procbox is not None:
        mail_counter += 1

return 'Succesfully processed {} emails!'.format(mail_counter) if mail_counter > 0 else 'No emails processed'

if name == “main”:
parser = argparse.ArgumentParser()
args = parser.parse_args()

b_olatt = True if args.olatt is None else False
b_olbody = True if args.olbody is None else False

if (not b_olatt and not b_olbody):
    sys.exit('No process choice made, choose between ol attachments saver (--olatt) and ol mail body saver (--olbody)!')
if args.outdest == '':
    sys.exit('No out destination defined using --outdest defined!')
if args.olfolder == '':
    sys.exit('No outlook folder to search mails for defined using --olfolder!')
if args.olprocfolder == '':
    sys.exit('No outlook folder to move processed mails to defined using --olprocfolder!')
proc = 'olatt' if b_olatt else 'olbody' if b_olbody else ''

run_ol_Script(args.outdest, args.olfiletype, args.olfolder, args.olprocfolder, False, proc)

Why did you install Python 2.7? That is a bad idea.

It is old, and no longer supported, and without paying money for a
private consultant, you probably won’t find anyone willing to spend time
helping you write new code in Python 2.

If you are on Windows, you can install Python 3 from the Microsoft App
Store. If you are on Linux, your distro will have Python 3 available
easily. I don’t know how to install Python on a Mac.