Microsoft Outlook Automation
This guide demonstrates how to automate the Microsoft Outlook desktop application using the pywin32 library. This allows you to send emails, read inbox messages, and manage folders directly through the installed Outlook client on Windows.
Note: This script requires Windows and the Microsoft Outlook desktop application to be installed and configured.
Modules Used:
pywin32: Provides access to the Windows API and COM objects (specificallywin32com.client).- argparse: To handle command-line arguments.
Installation
pip install pywin32
The Code
Save this as outlook_bot.py.
import win32com.client as win32
import argparse
import sys
import os
def get_outlook():
try:
# Connect to the running Outlook instance or start a new one
outlook = win32.Dispatch('outlook.application')
return outlook
except Exception as e:
print(f"Error connecting to Outlook: {e}")
return None
def send_email(to, subject, body, attachment=None):
outlook = get_outlook()
if not outlook: return
try:
# 0 represents a MailItem
mail = outlook.CreateItem(0)
mail.To = to
mail.Subject = subject
mail.Body = body
if attachment:
if os.path.exists(attachment):
mail.Attachments.Add(os.path.abspath(attachment))
else:
print(f"Warning: Attachment '{attachment}' not found.")
# mail.Display() # Uncomment to show the email window instead of sending immediately
mail.Send()
print(f"Email sent to {to}")
except Exception as e:
print(f"Error sending email: {e}")
def read_inbox(count=5):
outlook = get_outlook()
if not outlook: return
try:
# GetNamespace("MAPI") is required to access folders
mapi = outlook.GetNamespace("MAPI")
# 6 refers to the Inbox folder
inbox = mapi.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True) # Sort by received time descending
print(f"\n--- Latest {count} Emails ---")
# Iterate through the first 'count' messages
for i, message in enumerate(messages):
if i >= count:
break
try:
sender = message.SenderName
subject = message.Subject
received = message.ReceivedTime
print(f"[{received}] From: {sender} | Subject: {subject}")
except Exception:
# Some items might not be MailItems (e.g., meeting requests)
print(f"[{message.ReceivedTime}] <Non-Mail Item>")
except Exception as e:
print(f"Error reading inbox: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Outlook Automation Tool")
subparsers = parser.add_subparsers(dest="command", help="Command to run")
# Send Command
send_parser = subparsers.add_parser("send", help="Send an email")
send_parser.add_argument("to", help="Recipient email")
send_parser.add_argument("subject", help="Email subject")
send_parser.add_argument("body", help="Email body")
send_parser.add_argument("--attachment", help="Path to attachment file")
# Read Command
read_parser = subparsers.add_parser("read", help="Read latest emails")
read_parser.add_argument("-n", "--count", type=int, default=5, help="Number of emails to read")
args = parser.parse_args()
if args.command == "send":
send_email(args.to, args.subject, args.body, args.attachment)
elif args.command == "read":
read_inbox(args.count)
else:
parser.print_help()
Usage
# Read the last 5 emails
python outlook_bot.py read
# Send an email
python outlook_bot.py send recipient@example.com "Hello" "This is an automated message."