Message management - israel-dryer/Outlook-Python-Tutorial GitHub Wiki

In the last tutorial, we worked with the Folders collection. I briefly mentioned the Items collection. The Items collection is a collection of Outlook objects such as appointments, contacts, or messages.

Getting started

We'll start this project in a similar fashion as previously by importing the win32com library and dispatching and instance of Outlook.

import win32com.client as client

outlook = client.Dispatch('Outlook.Application')

We also need the NameSpace object to get access to the Outlook folders. In this case, we'll also use the GetDefaultFolder method to get the drafts folder.

namespace = outlook.GetNameSpace('MAPI')
drafts = namespace.GetDefaultFolder(16)

Indexing

You can index the Items collection in a similar way as the Folders collection:

# zero-based indexing > the index starts at 0
message = drafts.Items[0]
message = drafts.Items[1]

# one-based indexing > the index starts at 1
message = drafts.Items.Item(1)
message = drafts.Items.Item(2)

Properties & Methods

Items Collection

  • Items.Count : shows the number of items in a collection

Item Object The mail-item has many attributes you are already familiar with. You can find a full list in the documentation.

  • item.SenderName
  • item.SenderEmailAddress
  • item.Subject
  • item.Body

You can also change the attributes as well

item.Body = "This is new body text."

The following methods are also available and commonly used:

  • item.Copy()
  • item.Delete()
  • item.Send()

Iteration with the Items Collection

You can use the Items collection as an iterable. For example:

for message in drafts.Items:
    print(message.Subject)

Safe Iteration

You may be tempted to used this kind of iteration to send mail. However, you may remember that it's never a good idea to change an iterable while you are iterating over it. If you do, you will change the index of the items during iteration and you will be left with items unsent, not deleted, or a host of other problems. Instead, create a static reference to the items first, and then perform some action on them.

# create a static list of items
messages = list(drafts.Items)

# then perform some action on them
for message in messages:
    message.Send()

Filtering Items

You can also use iteration to filter mail items. You may not want to touch every item in the drafts folder. For example, suppose I have a bunch of drafts and some of them contain the word "Python" in the subject line. I want to only send these messages.

# filter only messages that contain the word "python" in the subject line
messages = [message for message in drafts.Items if 'python' in message.Subject.lower()]

# send the relevant messages
for message in messages:
    message.Send()

The use of the lower method above allows me to filter "case-insensitive".