[Tutor] Scripting Outlook

Tim Golden mail at timgolden.me.uk
Thu Mar 27 17:05:15 CET 2008

Justin Cardinal wrote:
> Can anyone direct me to some examples/documentation for using python to work
> with Outlook? So far, the most useful thing I've come across is a post from
> someone with problems adding an attachment:

and just for another example, here's some older code
which I post untested (altho' it certainly worked
once upon a time). If I get a chance I'll work it
into a how-do-i.


import os
from win32com.client import Dispatch, constants, gencache

outlook = gencache.EnsureDispatch ("Outlook.Application")

def send (self, to_people, cc_people=[], subject="", text="", 
   msg = outlook.CreateItem (constants.olMailItem)
   msg.Subject = subject
   msg.Body = text

   if type (to_people) == type (""):
     to_people = (to_people,)
   if type (cc_people) == type (""):
     cc_people = (cc_people,)
   recipients = []
   for person in to_people:
     recipient = msg.Recipients.Add (person)
     recipient.Type = constants.olTo
     recipients.append (recipient)
   for person in cc_people:
     recipient = msg.Recipients.Add (person)
     recipient.Type = constants.olCC
     recipients.append (recipient)

   if type (attachments) == type (""):
     attachments = (attachments,)
   for attachment in attachments:
     if os.path.isfile (attachment):
       msg.Attachments.Add (attachment)
       print "attachment %s skipped" % attachment

   all_resolved = 1
   for recipient in recipients:
     if not recipient.Resolve ():
       print "Unable to resolve " + recipient.Name
       all_resolved = 0

   if all_resolved:
     msg.Send ()
     print "Message sent"
     print "Message not sent"


More information about the Tutor mailing list