Outlook Integration

import win32com.client # win32 is library, client is sub library

## Reading mails
ol=win32com.client.Dispatch("outlook.application") # Dispatch is function, ol is object
inbox=ol.GetNamespace("MAPI").GetDefaultFolder(6) # it access the server of outlook, MAPI is microsoft API

for msg in inbox.Items: 
    if msg.unread==True and "QUERY" in msg.Subject.upper():
        print(msg.Sender, " : : ", msg.Sender.Address)
        print(msg.Recipients)
        print(msg.To)
        print(msg.CC)
        print(msg.Importance)
        print(msg.LastModificationTime)
        print()
        print(msg.Subject.upper()) # it will change in upper case
        print(msg.body)
        
## sending mails
olmailitem = 0x0 
obj=win32com.client.Dispatch("Outlook.application")

newmail= obj.CreateItem(olmailitem)
newmail.Subject="Testing Mail sent through python"
newmail.To="aparnabanerjee2311@outlook.com"
newmail.CC="aparnabanerjee2311@outlook.com"
newmail.Body="Hello class"
attach = "C:\\Users\\aparna\\OneDrive\\Desktop\\Python\\WA_Fn-UseC_-Accounts-Receivable.xlsx"
newmail.Attachments.Add(attach)
newmail.display()
#newmail.send

## Replying to mails
outlook=win32com.client.Dispatch("Outlook.application").GetNamespace("MAPI")
inbox=outlook.GetDefaultFolder(6) # 6 is used for inbox
msg=inbox.Items
for m in msg:
    if "QUERY" in m.Subject.upper():
        reply= m.ReplyAll()
        reply.Body= "hey"
        reply.Display()

Last updated