Skip to content

Instantly share code, notes, and snippets.

@bardal
Last active November 22, 2019 21:44
Show Gist options
  • Save bardal/b9f7779d699fff1908bdb4fba80a842c to your computer and use it in GitHub Desktop.
Save bardal/b9f7779d699fff1908bdb4fba80a842c to your computer and use it in GitHub Desktop.
Python Outlook automation with win32com - what evening appointments do I have coming up?
import win32com.client, datetime, time
# make sure we've got the outlook constants for Outlook 2010 - 'Microsoft Outlook 14.0 Object Library'
from win32com.client import gencache
gencache.EnsureModule('{00062FFF-0000-0000-C000-000000000046}', 0, 9, 4)
def _com_time_to_datetime(pytime):
return datetime.datetime(month=pytime.month, day=pytime.day, year=pytime.year,
hour=pytime.hour, minute=pytime.minute, second=pytime.second)
#config
weeksAhead = 8
email_address = "me@somewhere.com"
outlook = win32com.client.gencache.EnsureDispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")
folder = mapi.GetDefaultFolder(win32com.client.constants.olFolderCalendar)
startDate = datetime.date.today()
endDate = startDate + datetime.timedelta(weeks=weeksAhead)
formatDateString = "%d %B %Y %I:%M%p"
dateRangeQuery ='[Start] >= "{}" AND [End] <= "{}"'.format(startDate.strftime(formatDateString), endDate.strftime(formatDateString))
calendarItems = folder.Items
calendarItems.IncludeRecurrences = True
calendarItems.Sort("[Start]", False)
calendarItems = calendarItems.Restrict(dateRangeQuery)
calendarSummary = "From {} to {}\n\n".format(startDate.strftime("%a %d %b"), endDate.strftime("%a %d %b"))
for item in calendarItems:
if item.End.hour > 18:
start = _com_time_to_datetime(item.Start).strftime("%a %d %b %H:%M")
end = _com_time_to_datetime(item.End).strftime("%H:%M")
calendarSummary += "{}-{} {}\n".format(start, end, item.Subject)
message = outlook.CreateItem(win32com.client.constants.olMailItem)
message.BodyFormat = win32com.client.constants.olFormatPlain
message.To = email_address
message.Subject = "Evening calendar entries - next "+str(weeksAhead)+" weeks"
message.Body = calendarSummary
for recipient in message.Recipients:
recipient.Resolve()
message.Display()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment