Email Handling in Python- Outlook Version

3 minute read

My daily work involves a lot email handling. Believe a lot people have experienced the same thing with me. This post is going to teach you not feel overwhelmed by automating your emails it in Python. My company use Outlook (think most of financial services firms use Outlook as well). I will use exchangelib package in this post

It’s really important to start email automation if you have this situation.

Now I will illustrate how to connect and send emails in Python

# load packages
import datetime
import pandas as pd
import datetime as dt
from exchangelib import ServiceAccount, Configuration, Account, DELEGATE, HTMLBody, Credentials

Set up connections with Outlook

From  = 'your email address'
password = 'your email password'
servername = 'your server name' #check with your company admin for servername. 


def connect(server, email, username, password):
    cred = Credentials(username = username, password = password)
    config =  Configuration(server= servername, credentials = cred)
    return Account(primary_smtp_address=email, autodiscover= False, config= config, access_type=DELEGATE)

a= connect(servername,'your email address', From, password)

I works in broker firm. We usually have multiple custodians who send daily reports to us. Usually I would save the attachment to my local drive for further analysis.

for item in a.inbox.children: #I created a subfolder under inbox. you can just use inbox as well.
    for emailz in item.all().order_by('-datetime_received')[:1]:
        for attachment in emailz.attachments:
            if isinstance(attachment, FileAttachment):
                local_path = os.path.join('your path', attachment.name)
                with open(local_path, 'wb') as f, attachment.fp as fp:
                    buffer = fp.read(1024)
                    while buffer:
                        f.write(buffer)
                        buffer = fp.read(1024)
                        files = local_path
                    print('Saved attachment to', local_path)

Then please perform your data analysis. Once done, you can use the followin code to send out emails automatically

m= Message(
    account= a,
    folder = a.sent,
    subject = 'please define your subject'
    body = 'please add your body',
    to_recipents =[Mailbox(email_address = 'xxx')]
)
m.attach('your file')
m.send_and_save()

This can save a lot time! Try it now!