<jupyter_start><jupyter_text>Outlook 2016 Email Examples Using Python **Dependencies:**- win32com library to interface with Microsoft Office products    - Install with conda at DOS prompt> conda install pywin32 **Optional Dependencies:**- pandas **Additional References:**- Microsoft's Outlook COM [reference](https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.mailitem_properties.aspx) **NOTE:** Script uses local Outlook account  Sending Email<jupyter_code>import win32com.client as win32

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = "<EMAIL>; <EMAIL>"
mail.Subject = 'Your email subject'
mail.HTMLBody = "This email was automatically sent via Python Script"
mail.Send()<jupyter_output><empty_output><jupyter_text>Reading last email StackOverflow [example](http://stackoverflow.com/questions/31619012/extract-senders-email-address-from-outlook-exchange-in-python-using-win32) that explains for the need to check the message Class for getting the right email format.<jupyter_code>import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
                                    # the inbox. You can change that number to reference
                                    # any other folder
all_inbox = inbox.Items
message = all_inbox.GetLast()

print("### Email Subject  ##")
print(message.subject, '\n')

print("###  Email Body  ###")
print(message.body)

print("###  Date Email Sent  ###")
print(message.SentOn, '\n')

print("###  Date Email Received  ###")
print(message.ReceivedTime, '\n')

print("###  Sender's First and Last Name  ###")
print(message.sender, '\n')

if message.Class == 43:
    if message.senderemailtype=='EX':
        print("###  Sender's email  ###")
        print(message.Sender.GetExchangeUser().PrimarySmtpAddress)
    else:
        print("###  Sender's email  ###")
        print(message.SenderEmailAddress)<jupyter_output><empty_output><jupyter_text>To get list of top email senders:<jupyter_code>import pandas as pd
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items

df = pd.DataFrame()  # Create empty dataframe that we will be populating in the FOR loop
for msg in all_inbox:
    if msg.Class==43:
        if msg.SenderEmailType=='EX':
            # The format of the date stored in Outlook is giving errors, so forcing it to str format
            df = df.append({'SENDER':msg.Sender.GetExchangeUser().PrimarySmtpAddress, 
                            'DATE':str(msg.ReceivedTime)}, ignore_index=True)
        else:
            # The format of the date stored in Outlook is giving errors, so forcing it to str format
            df = df.append({'SENDER':msg.SenderEmailAddress, 'DATE':str(msg.ReceivedTime)}, ignore_index=True)<jupyter_output><empty_output><jupyter_text>Because Outlook's date format is a non-standard format, it was giving errors.  As a workaround, it was stored as an object or string.  Then later, we will change the data type to date format.<jupyter_code>df.dtypes
df.head()<jupyter_output><empty_output><jupyter_text>Change the data type of the ```DATE``` column to an actual date type so that we can query it as if it was a date:<jupyter_code>df.DATE = pd.to_datetime(df.DATE)<jupyter_output><empty_output><jupyter_text>Note the ```DATE``` column is now a date format<jupyter_code>df.dtypes
df.head()<jupyter_output><empty_output><jupyter_text>Finally, here is list of top email senders using value_counts() function:<jupyter_code>df.SENDER.value_counts()<jupyter_output><empty_output><jupyter_text>No surprise <EMAIL> sends the most emails to me :-)  Filter inbox emails by received date or by Sender  For example, to get emails received between 2017-03-21 and 2017-03-22:<jupyter_code>filter_by_date = df.query("DATE >= '2017-03-21' and DATE <= '2017-03-22'")
filter_by_date<jupyter_output><empty_output><jupyter_text>To get list of emails from a specific sender:<jupyter_code>filter_by_email = df.query("SENDER == '<EMAIL>'")
filter_by_email<jupyter_output><empty_output><jupyter_text>To obtain list of other Outlook folders and other useful objects:<jupyter_code>from win32com.client import Dispatch

outlook=Dispatch("Outlook.Application").GetNamespace("MAPI")
for i in range(50):
    try:
        box = outlook.GetDefaultFolder(i)
        name = box.Name
        print(i, name)
    except:
        pass<jupyter_output><empty_output><jupyter_text>To summarize sent emails, from above, we can re-use the previous script by referencing "5" in the following:<jupyter_code>outlook.GetDefaultFolder("5")   # to access "Sent" folder
import pandas as pd
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
sentbox = outlook.GetDefaultFolder("5")
all_sentbox = sentbox.Items

df = pd.DataFrame()  # Create empty dataframe that we will be populating in the FOR loop
for msg in all_sentbox:
    for recipient in msg.Recipients:
        print(recipient.address)
        
for msg in all_inbox:
    if msg.Class==43:
        if msg.SenderEmailType=='EX':
            # The format of the date stored in Outlook is giving errors, so forcing it to str format
            df = df.append({'SENDER':msg.Sender.GetExchangeUser().PrimarySmtpAddress, 
                            'DATE':str(msg.ReceivedTime)}, ignore_index=True)
        else:
            # The format of the date stored in Outlook is giving errors, so forcing it to str format
            df = df.append({'SENDER':msg.SenderEmailAddress, 'DATE':str(msg.ReceivedTime)}, ignore_index=True)
import pandas as pd
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
sentbox = outlook.GetDefaultFolder("5")
all_sentbox = sentbox.Items

df = pd.DataFrame()  # Create empty dataframe that we will be populating in the FOR loop
        
for msg in all_sentbox:
    if msg.Class==43:
        if msg.SenderEmailType=='EX':
            print('Sender: ', msg.Sender.GetExchangeUser().PrimarySmtpAddress)
            for recipient in msg.Recipients:
                print(recipient.GetExchangeUser().PrimarySmtpAddress)
        else:
            for recipient in msg.Recipients:
                print(recipient.address)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10924891371818746, 'fraction_numerical': 0.01334574798261949, 'mean_word_length': 4.123211446740859, 'pattern_counts': {'":': 0, '<': 50, '<?xml version=': 0, '>': 51, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '234751', 'license': 'MIT', 'n_tokens_mistral': 2033, 'n_tokens_neox': 1909, 'n_words': 551, 'path': 'jupyter_notebooks/email/Outlook2016_win32com.ipynb', 'repo_name': 'manual123/Nacho-Jupyter-Notebooks', 'size': '6510'}