This module is an ORM for your Exchange mailbox, providing Django-style access to all your data. It is a platform-independent, well-performing, well-behaving, well-documented, well-tested and simple interface for communicating with an on-premise Microsoft Exchange 2007-2016 server or Office365 using Exchange Web Services (EWS). Among other things, it implements autodiscover, and functions for searching, creating, updating, deleting, exporting and uploading calendar, mailbox, task, contact and distribution list items.

Apart from this documentation, we also provide online source code documentation.

Table of Contents


You can install this package from PyPI:

pip install exchangelib

The default installation does not support Kerberos or SSPI. For additional Kerberos or SSPI support, install with the extra  kerberos  or  sspi  dependencies (please note that SSPI is only supported on Windows):

pip install exchangelib[kerberos]
pip install exchangelib[sspi]

To get both, install as:

pip install exchangelib[complete]

To install the very latest code, install directly from GitHub instead:

pip install git+

exchangelib  uses the  lxml  package, and  pykerberos  to support Kerberos authentication. To be able to install these, you may need to install some additional operating system packages.

On Ubuntu:

apt-get install libxml2-dev libxslt1-dev
# For Kerberos support, also install these:
apt-get install libkrb5-dev build-essential libssl-dev libffi-dev python-dev

On CentOS:

# For Kerberos support, install these:
yum install gcc python-devel krb5-devel krb5-workstation python-devel

On FreeBSD,  pip  needs a little help:

pkg install libxml2 libxslt
CFLAGS=-I/usr/local/include pip install lxml
# For Kerberos support, also install these:
pkg install krb5
CFLAGS=-I/usr/local/include pip install kerberos pykerberos

For other operating systems, please consult the documentation for the Python package that fails to install.

Setup and connecting

from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials
# Specify your credentials. Username is usually in WINDOMAIN\username format,
# where WINDOMAIN is the name of the Windows Domain your username is connected
# to, but some servers also accept usernames in PrimarySMTPAddress
# ('') format (Office365 requires it). UPN format is also
# supported, if your server expects that.
credentials = Credentials(username='MYWINDOMAIN\\myuser', password='topsecret')
# If you're running long-running jobs, you may want to enable fault-tolerance.
# Fault-tolerance means that requests to the server do an exponential backoff
# and sleep for up to a certain threshold before giving up, if the server is
# unavailable or responding with error messages. This prevents automated scripts
# from overwhelming a failing or overloaded server, and hides intermittent
# service outages that often happen in large Exchange installations.

# An Account is the account on the Exchange server that you want to connect to.
# This can be the account associated with the credentials you connect with, or
# any other account on the server that you have been granted access to. If, for
# example, you want to access a shared folder, create an Account instance using
# the email address of the account that the shared folder belongs to, and access
# the shared folder through this account.

# 'primary_smtp_address' is the primary SMTP address assigned the account. If
# you enable autodiscover, an alias address will work, too. In this case,
# 'Account.primary_smtp_address' will be set to the primary SMTP address.
my_account = Account(
primary_smtp_address='', credentials=credentials,
autodiscover=True, access_type=DELEGATE
johns_account = Account(
primary_smtp_address='', credentials=credentials,
autodiscover=True, access_type=DELEGATE
marys_account = Account(
primary_smtp_address='', credentials=credentials,
autodiscover=True, access_type=DELEGATE
still_marys_account = Account(
primary_smtp_address='', credentials=credentials,
autodiscover=True, access_type=DELEGATE
# Full autodiscover data is available on the Account object:
# Set up a target account and do an autodiscover lookup to find the EWS endpoint
account = Account(
primary_smtp_address='', credentials=credentials, 
autodiscover=True, access_type=DELEGATE
# If your credentials have been given impersonation access to the target
# account, set a different 'access_type':
account = Account(
primary_smtp_address='', credentials=credentials, 
autodiscover=True, access_type=IMPERSONATION
# Autodiscover needs to make some DNS queries. We use the dnspython package for
# that. Here's an example of customizing the way the dns.resolver.Resolver
# object is created:
from exchangelib.autodiscover import Autodiscovery
Autodiscovery.DNS_RESOLVER_ATTRS['edns'] = False  # Disable EDNS queries

Optimizing connections

from exchangelib import DELEGATE, Account, Configuration, Credentials, NTLM, \
Build, Version
# According to MSDN docs, you can avoid a per-request AD lookup if you specify
# the UPN or SID of the account when you are using impersonation. To do this,
# set one of these values. EWS cannot provide you with these values - you have
# to fetch them by some other means, e.g. via AD lookup:
account = Account(...)
account.identity.sid = 'S-my-sid'
account.identity.upn = ''
# If the server doesn't support autodiscover, or you want to avoid the overhead
# of autodiscover, use a Configuration object to set the hostname instead:
credentials = Credentials(...)
config = Configuration(server='', credentials=credentials)
# For accounts that are known to be hosted on Office365, there's no need to use
# autodiscover. Here's the server to use for Office365:
config = Configuration(server='', credentials=credentials)
account = Account(primary_smtp_address='', config=config,
autodiscover=False, access_type=DELEGATE)
# 'exchangelib' will attempt to guess the server version and authentication
# method. If you have a really bizarre or locked-down installation and the
# guessing fails, or you want to avoid the extra network traffic, you can set
# the auth method and version explicitly instead:
version = Version(build=Build(15, 0, 12, 34))
config = Configuration(
server='', credentials=credentials, version=version,
# By default, 'exchangelib' will only create 1 connection to the server. If you
# are using threads to send multiple requests concurrently, you may want to
# increase this limit. The Exchange server may have rate-limiting policies in
# place for the connecting credentials, so make sure to agree with your Exchange
# admins before increasing this value.
config = Configuration(server='', max_connections=10)

Fault tolerance

from exchangelib import Account, FaultTolerance, Configuration, Credentials
from exchangelib.autodiscover import Autodiscovery
# By default, we fail on all exceptions from the server. If you want to enable
# fault tolerance, add a retry policy to your configuration. We will then retry
# on certain transient errors. By default, we back off exponentially and retry
# for up to an hour. This is configurable:
credentials = Credentials(...)
config = Configuration(
retry_policy=FaultTolerance(max_wait=3600), credentials=credentials
account = Account(primary_smtp_address='', config=config)
# Autodiscovery will also use this policy, but only for the final autodiscover
# endpoint. Here's how to change the policy for connecting to autodiscover
# candidate servers.
Autodiscovery.INITIAL_RETRY_POLICY = FaultTolerance(max_wait=30)

Kerberos and SSPI authentication

from exchangelib import Configuration, GSSAPI, SSPI
# Kerberos and SSPI authentication are supported via the GSSAPI and SSPI auth
# types.
config = Configuration(auth_type=GSSAPI)
config = Configuration(auth_type=SSPI)

Certificate Based Authentication (CBA)

from exchangelib import Configuration, BaseProtocol, CBA, TLSClientAuth
TLSClientAuth.cert_file = '/path/to/client.pem'
BaseProtocol.HTTP_ADAPTER_CLS = TLSClientAuth
config = Configuration(auth_type=CBA)

OAuth authentication

# OAuth is supported via the OAUTH2 auth type and the OAuth2Credentials class.
# Use OAuth2AuthorizationCodeCredentials for the authorization code flow (useful
# for applications that access multiple accounts).
from exchangelib import Configuration, OAuth2Credentials, \
OAuth2AuthorizationCodeCredentials, Identity, OAUTH2
from oauthlib.oauth2 import OAuth2Token
credentials = OAuth2Credentials(
client_id='MY_ID', client_secret='MY_SECRET', tenant_id='TENANT_ID'
# The OAuth2 flow may need to have impersonation headers set. If you get
# impersonation errors, add information about the account that the OAuth2
# credentials was created for:
credentials = OAuth2Credentials(
..., identity=Identity(primary_smtp_address='')
credentials = OAuth2AuthorizationCodeCredentials(
..., identity=Identity(upn='')
credentials = OAuth2AuthorizationCodeCredentials(
client_id='MY_ID', client_secret='MY_SECRET', authorization_code='AUTH_CODE'
credentials = OAuth2AuthorizationCodeCredentials(
client_id='MY_ID', client_secret='MY_SECRET',
config = Configuration(credentials=credentials, auth_type=OAUTH2)
# Applications using the authorization code flow that let exchangelib refresh
# access tokens for them probably want to store the refreshed tokens so users
# don't have to re-authorize. Subclass OAuth2AuthorizationCodeCredentials and
# override on_token_auto_refreshed():
class MyCredentials(OAuth2AuthorizationCodeCredentials):
def on_token_auto_refreshed(self, access_token):
# Let the object update its internal state!
# For applications that use the authorization code flow and rely on an external
# provider to refresh access tokens (and thus are unable to provide a client ID
# and secret to exchangelib), subclass OAuth2AuthorizationCodeCredentials and
# override refresh().
class MyCredentials(OAuth2AuthorizationCodeCredentials):
def refresh(self):
self.access_token = ...

Caching autodiscover results

from exchangelib import Configuration, Credentials, Account, DELEGATE
# If you're connecting to the same account very often, you can cache the
# autodiscover result for later so you can skip the autodiscover lookup:
account = Account(...)
ews_url = account.protocol.service_endpoint
ews_auth_type = account.protocol.auth_type
primary_smtp_address = account.primary_smtp_address
# This one is optional. It is used as a hint to the initial connection and
# avoids one or more roundtrips to guess the correct Exchange server version.
version = account.version
# You can now create the Account without autodiscovery, using the cached values:
credentials = Credentials(...)
config = Configuration(
service_endpoint=ews_url, credentials=credentials, auth_type=ews_auth_type,
account = Account(
config=config, autodiscover=False, 
# Autodiscover can take a lot of time, specially the part that figures out the
# autodiscover server to contact for a specific email domain. For this reason,
# we will create a persistent, per-user, on-disk cache containing a map of
# previous, successful domain -> autodiscover server lookups. This cache is
# shared between processes and is not deleted when your program exits.

# A cache entry for a domain is removed automatically if autodiscovery fails for
# an email in that domain. It's possible to clear the entire cache completely if
# you want:
from exchangelib.autodiscover import clear_cache

Proxies and custom TLS validation

If you need proxy support or custom TLS validation, you can supply a custom ‘requests’ transport adapter class, as described in

Here’s an example using different custom root certificates depending on the server to connect to:

from urllib.parse import urlparse
import requests.adapters
from exchangelib.protocol import BaseProtocol
class RootCAAdapter(requests.adapters.HTTPAdapter):
"""An HTTP adapter that uses a custom root CA certificate at a hard coded
def cert_verify(self, conn, url, verify, cert):
cert_file = {
'': '/path/to/',
'mail.internal': '/path/to/mail.internal.crt',
super().cert_verify(conn=conn, url=url, verify=cert_file, cert=cert)
# Tell exchangelib to use this adapter class instead of the default
BaseProtocol.HTTP_ADAPTER_CLS = RootCAAdapter

Here’s an example of adding proxy support:

import requests.adapters
from exchangelib.protocol import BaseProtocol
class ProxyAdapter(requests.adapters.HTTPAdapter):
def send(self, *args, **kwargs):
kwargs['proxies'] = {
'http': '',
'https': '',
return super().send(*args, **kwargs)
# Tell exchangelib to use this adapter class instead of the default
BaseProtocol.HTTP_ADAPTER_CLS = ProxyAdapter

exchangelib  provides a sample adapter which ignores TLS validation errors. Use at own risk.

from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
# Tell exchangelib to use this adapter class instead of the default
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter


You can supply a custom ‘User-Agent’ for your application. By default,  exchangelib  will use:  exchangelib/<version> (python-requests/<version>)

Here’s an example using different User-Agent:

from exchangelib.protocol import BaseProtocol
# Tell exchangelib to use this user-agent instead of the default
BaseProtocol.USERAGENT = "Auto-Reply/0.1.0"


All wellknown folders are available as properties on the account, e.g. as  account.rootaccount.calendaraccount.trashaccount.inboxaccount.outboxaccount.sentaccount.junkaccount.tasks  and  account.contacts .

# There are multiple ways of navigating the folder tree and searching for
# folders. Globbing and absolute path may create unexpected results if your
# folder names contain slashes.

# The folder structure is cached after first access to a folder hierarchy. This
# means that external changes to the folder structure will not show up until you
# clear the cache. Here's how to clear the cache of each of the currently
# supported folder hierarchies:
from exchangelib import Account, Folder
a = Account(...)
some_folder = a.root / 'Some Folder'
# Returns the root of the folder structure, at any level. Same as Account.root
some_folder.children  # A generator of child folders
some_folder.absolute  # Returns the absolute path, as a string
# A generator returning all subfolders at arbitrary depth this level
# Globbing uses the normal UNIX globbing syntax, but case-insensitive
some_folder.glob('foo*')  # Return child folders matching the pattern
some_folder.glob('*/foo')  # Return subfolders named 'foo' in any child folder
some_folder.glob('**/foo')  # Return subfolders named 'foo' at any depth
some_folder / 'sub_folder' / 'even_deeper' / 'leaf'  # Works like pathlib.Path
# You can also drill down into the folder structure without using the cache.
# This works like the single slash syntax, but does not start by creating a
# cache the folder hierarchy. This is useful if your account contains a huge
# number of folders, and you already know where to go.
some_folder // 'sub_folder' // 'even_deeper' // 'leaf'  # returns some_folder and all parents, as Folder instances
# tree() returns a string representation of the tree structure at a given level
├── inbox
│   └── todos
└── archive
├── Last Job
├── exchangelib issues
└── Mom
# Folders have some useful counters:
# Update the counters
# Folders can be created, updated and deleted:
f = Folder(parent=a.inbox, name='My New Folder') = 'My New Subfolder'
# Delete all items in a folder
# Also delete all subfolders in the folder
# Recursively delete all items in a folder, and all subfolders and their
# content. This is like `empty(delete_sub_folders=True)` but attempts to protect
# distinguished folders from being deleted. Use with caution!
# Folders support getting, creating, updating and deleting Master Category
# Lists, also known as User Configuration objects. Supported key and value types
# for the 'dictionary' attribute are: bool, int, bytes, str, tuples of str,
# datetime, EWSDateTime, and the 'Byte' type which we emulate in Python as a
# 1-length bytes.
dictionary={'foo': 'bar', 123: 'a', 'b': False},
config = f.get_user_configuration(name='SomeName')
config.dictionary  # {'foo': 'bar', 123: 'a', 'b': False}
config.xml_data  # b'<foo>bar</foo>'
config.binary_data  # b'XXX'

dictionary={'bar': 'foo', 456: 'a', 'b': True},

Dates, datetimes and timezones

EWS has some special requirements on datetimes and timezones. You may use regular  datetime.*  and  zoneinfo  objects as input, but all methods return date values as the special  EWSDateEWSDateTime  and  EWSTimeZone  classes. Thes classes are all subclasses of  datetime.*  or  zoneinfo.ZoneInfo  so you should be able to use them as regular date objects.

from datetime import datetime, timedelta
import pytz
import zoneinfo
except ImportError:
from backports import zoneinfo
from exchangelib import EWSTimeZone, EWSDateTime, EWSDate, UTC, UTC_NOW
# EWSTimeZone works just like zoneinfo.ZoneInfo()
tz = EWSTimeZone('Europe/Copenhagen')
# You can also get the local timezone defined in your operating system
tz = EWSTimeZone.localzone()
# EWSDate and EWSDateTime work just like datetime.datetime and
# Always create timezone-aware datetimes:
localized_dt = EWSDateTime(2017, 9, 5, 8, 30, tzinfo=tz)
right_now =
# Datetime math works transparently
two_hours_later = localized_dt + timedelta(hours=2)
two_hours = two_hours_later - localized_dt
two_hours_later += timedelta(hours=2)
# Dates
my_date = EWSDate(2017, 9, 5)
today =
also_today =
also_today += timedelta(days=10)
# UTC helpers. 'UTC' is the UTC timezone as an EWSTimeZone instance.
# 'UTC_NOW' returns a timezone-aware UTC timestamp of current time.
right_now_in_utc =
right_now_in_utc = UTC_NOW()
# 'pytz', 'dateutil' and `zoneinfo` timezones can be converted to EWSTimeZone
pytz_tz = pytz.timezone('Europe/Copenhagen')
tz = EWSTimeZone.from_timezone(pytz_tz)
dateutil_tz ='Europe/Copenhagen')
tz = EWSTimeZone.from_timezone(dateutil_tz)
zoneinfo_tz = zoneinfo.ZoneInfo('Europe/Copenhagen')
tz = EWSTimeZone.from_timezone(zoneinfo_tz)
# Python datetime objects can be converted using from_datetime(). Make sure
# values are timezone-aware and tzinfo is an EWSTimeZone or ZoneInfo instance.
py_dt = datetime(2017, 12, 11, 10, 9, 8, tzinfo=tz)
ews_now = EWSDateTime.from_datetime(py_dt)

Creating, updating, deleting, sending, moving, archiving, marking as junk

# Here's an example of creating a calendar item in the user's standard calendar.
# If you want to access a non-standard calendar, choose a different one from
# account.folders[Calendar].
# You can create, update and delete single items:
from exchangelib import Account, CalendarItem, Message, Mailbox, \
FileAttachment, HTMLBody
from exchangelib.items import SEND_ONLY_TO_ALL, SEND_ONLY_TO_CHANGED
from import DistinguishedFolderId
a = Account(...)
item = CalendarItem(folder=a.calendar, subject='foo')  # This gives the item an 'id' and a 'changekey' value
# Send a meeting invitation to attendees
# Update a field. All fields have a corresponding Python type that must be used.
item.subject = 'bar'
# Print all available fields on the 'CalendarItem' class. Beware that some
# fields are read-only, or read-only after the item has been saved or sent, and
# some fields are not supported on old versions of Exchange.
print(CalendarItem.FIELDS)  # When the items has an item_id, this will update the item
# Only updates certain fields. Accepts a list of field names.['subject'])
# Send invites only to attendee changes
item.delete()  # Hard deletion
# Send cancellations to all attendees
item.soft_delete()  # Delete, but keep a copy in the recoverable items folder
item.move_to_trash()  # Move to the trash folder
item.move(a.trash)  # Also moves the item to the trash folder
item.copy(a.trash)  # Creates a copy of the item to the trash folder
# Archives the item to inbox of the archive mailbox
# Block sender and move item to junk folder
item.mark_as_junk(is_junk=True, move_item=True)
# You can also send emails. If you don't want a local copy:
m = Message(
subject='Daily motivation',
body='All bodies are beautiful',
# Simple strings work, too
    cc_recipients=['', ''],
],  # Or a mix of both
# Or, if you want a copy in e.g. the 'Sent' folder
m = Message(
subject='Daily motivation',
body='All bodies are beautiful',
# Likewise, you can reply to and forward messages that are stored in your
# mailbox (i.e. they have an item ID).
m = a.sent.get(subject='Daily motivation')
subject='Re: Daily motivation',
body='I agree',
to_recipients=['', '']
m.reply_all(subject='Re: Daily motivation', body='I agree')
subject='Fwd: Daily motivation',
body='Hey, look at this!', 
to_recipients=['', '']
# You can also edit a draft of a reply or forward
forward_draft = m.create_forward(
subject='Fwd: Daily motivation',
body='Hey, look at this!',
to_recipients=['', '']
).save(a.drafts) # gives you back the item
forward_draft.reply_to = ['']
name='my_file.txt', content='hello world'.encode('utf-8'))
# Now our forward has an extra reply_to field and an extra attachment.
# EWS distinguishes between plain text and HTML body contents. If you want to
# send HTML body content, use the HTMLBody helper. Clients will see this as HTML
# and display the body correctly:
item.body = HTMLBody(
'<html><body>Hello happy <blink>OWA user!</blink></body></html>'

Bulk operations

# Build a list of calendar items
import datetime
import zoneinfo
except ImportError:
from backports import zoneinfo
from exchangelib import Account, CalendarItem, Attendee, Mailbox
from import DistinguishedFolderId
a = Account(...)
tz = zoneinfo.ZoneInfo('Europe/Copenhagen')
year, month, day = 2016, 3, 20
calendar_items = []
for hour in range(7, 17):
start=datetime.datetime(year, month, day, hour, 30, tzinfo=tz),
end=datetime.datetime(year, month, day, hour + 1, 15, tzinfo=tz),
subject='Test item',
body='Hello from Python',
categories=['foo', 'bar'],
required_attendees = [Attendee(
# Create all items at once
return_ids = a.bulk_create(folder=a.calendar, items=calendar_items)
# Bulk fetch, when you have a list of item IDs and want the full objects.
# Returns a generator.
calendar_ids = [(, i.changekey) for i in calendar_items]
items_iter = a.fetch(ids=calendar_ids)
# If you only want some fields, use the 'only_fields' attribute
items_iter = a.fetch(ids=calendar_ids, only_fields=['start', 'subject'])
# Bulk update items. Each item must be accompanied by a list of attributes to
# update.
updated_ids = a.bulk_update(
items=[(i, ('start', 'subject')) for i in calendar_items]
# Move many items to a new folder
new_ids = a.bulk_move(ids=calendar_ids, to_folder=a.other_calendar)
# Send draft messages in bulk
message_ids = a.drafts.all().only('id', 'changekey')
new_ids = a.bulk_send(ids=message_ids, save_copy=False)
# Delete in bulk
delete_results = a.bulk_delete(ids=calendar_ids)
# Archive in bulk
delete_results = a.bulk_archive(
ids=calendar_ids, to_folder=DistinguishedFolderId('inbox')
# Bulk delete items found as a queryset
# Likewise, you can bulk send, copy, move or archive items found in a QuerySet
# All kwargs are passed on to the equivalent bulk methods on the Account
is_junk=True, move_item=True
# You can change the default page size of bulk operations if you have a slow or
# busy server.


Searching is modeled after the Django QuerySet API, and a large part of the API is supported. Like in Django, the QuerySet is lazy and doesn’t fetch anything before the QuerySet is iterated. QuerySets support chaining, so you can build the final query in multiple steps, and you can re-use a base QuerySet for multiple sub-searches. The QuerySet is an iterator.

Here are some examples of using the API:

import datetime
from exchangelib import Account, FolderCollection, Q, Message
a = Account(...)
# Not all fields on an item support searching. Here's the list of options for
# Message items.
print([ for f in Message.FIELDS if f.is_searchable])
all_items = a.inbox.all()  # Get everything
all_items_without_caching = a.inbox.all()
# Chain multiple modifiers to refine the query
filtered_items = a.inbox.filter(subject__contains='foo')\
# Delete all items returned by the QuerySet
status_report = a.inbox.all().delete()
start = datetime.datetime(2017, 1, 1, tzinfo=a.default_timezone)
end = datetime.datetime(2018, 1, 1, tzinfo=a.default_timezone)
# Filter by a date range
items_for_2017 = a.calendar.filter(start__range=(start, end))
# Same as filter() but throws an error if exactly one item isn't returned
item = a.inbox.get(subject='unique_string')
# If you only have the ID and possibly the changekey of an item, you can get the
# full item:
a.inbox.get(id='AAMkADQy=', changekey='FwAAABYA')
# You can sort by a single or multiple fields. Prefix a field with '-' to
# reverse the sorting. Sorting is efficient since it is done server-side, except
# when a calendar view sorting on multiple fields.
ordered_items = a.inbox.all().order_by('subject')
reverse_ordered_items = a.inbox.all().order_by('-subject')
# Indexed properties can be ordered on their individual components
sorted_by_home_street = a.contacts.all().order_by(
# Beware that sorting is done client-side here
a.calendar.view(start=start, end=end).order_by('subject', 'categories')
# Counting and exists
n = a.inbox.all().count()  # Efficient counting
folder_is_empty = not a.inbox.all().exists()  # Efficient tasting

# Restricting returned attributes
sparse_items = a.inbox.all().only('subject', 'start')
# Dig deeper on indexed properties
sparse_items = a.contacts.all().only('phone_numbers')
sparse_items = a.contacts.all().only('phone_numbers__CarPhone')
sparse_items = a.contacts.all().only('physical_addresses__Home__street')
# Return values as dicts, not objects
ids_as_dict = a.inbox.all().values('id', 'changekey')
# Return values as nested lists
values_as_list = a.inbox.all().values_list('subject', 'body')
# Return values as a flat list
all_subjects = a.inbox.all().values_list(
'physical_addresses__Home__street', flat=True
# A QuerySet can be indexed and sliced like a normal Python list. Slicing and
# indexing of the QuerySet is efficient because it only fetches the necessary
# items to perform the slicing. Slicing from the end is also efficient, but then
# you might as well reverse the sorting.

# Efficient. We only fetch 10 items
first_ten = a.inbox.all().order_by('-subject')[:10]
# Efficient, but convoluted
last_ten = a.inbox.all().order_by('-subject')[:-10]
# Efficient. We only fetch 10 items
next_ten = a.inbox.all().order_by('-subject')[10:20]
# Efficient. We only fetch 1 item
single_item = a.inbox.all().order_by('-subject')[34298]
# Efficient. We only fetch 10 items
ten_items = a.inbox.all().order_by('-subject')[3420:3430]
# This is just stupid, but works
random_emails = a.inbox.all().order_by('-subject')[::3]
# The syntax for filter() is modeled after Django QuerySet filters. The
# following filter lookup types are supported. Some lookups only work with
# string attributes. Range and less/greater operators only work for date or
# numerical attributes. This is determined by the field type.
# Some attributes are not searchable at all via EWS. This is determined by the
# "is_searchable" attribute on the field.

# List the field name and field type of searchable fields for a given item type
for f in Message.FIELDS:
if f.is_searchable:
print(, f)
# No restrictions. Return all items.
qs = a.calendar.all()
# Returns items where subject is exactly 'foo'. Case-sensitive
# Returns items within range
qs.filter(start__range=(start, end)) 
# Return items where subject is either 'foo' or 'bar'
qs.filter(subject__in=('foo', 'bar'))
# Returns items where subject is not 'foo'
# Returns items starting after 'dt'
# Returns items starting on or after 'dt'
# Returns items starting before 'dt'
# Returns items starting on or before 'dt'
# Same as filter(subject='foo')
# Returns items where subject is 'foo', 'FOO' or 'Foo'
# Returns items where subject contains 'foo'
# Returns items where subject contains 'foo', 'FOO' or 'Foo'
# Returns items where subject starts with 'foo'
# Returns items where subject starts with 'foo', 'FOO' or 'Foo'
# Returns items that have at least one category assigned, i.e. the field exists
# on the item on the server.
# Returns items that have no categories set, i.e. the field does not exist on
# the item on the server.
# WARNING: Filtering on the 'body' field is not fully supported by EWS. There
# seems to be a window before some internal search index is populated where
# case-sensitive or case-insensitive filtering for substrings in the body
# element incorrectly returns an empty result, and sometimes the result stays
# empty.

# filter() also supports EWS QueryStrings. Just pass the string to filter().
# QueryStrings cannot be combined with other filters. We make no attempt at
# validating the syntax of the QueryString - we just pass the string verbatim to
# EWS.
# Read more about the QueryString syntax here:
# filter() also supports Q objects that are modeled after Django Q objects, for
# building complex boolean logic search expressions.
q = (
Q(subject__iexact='foo') | Q(subject__contains='bar')
) & ~Q(subject__startswith='baz')
# In this example, we filter by categories so we only get items created by us.
start__lt=datetime.datetime(2019, 1, 1, tzinfo=a.default_timezone),
end__gt=datetime.datetime(2019, 1, 31, tzinfo=a.default_timezone),
categories__contains=['foo', 'bar'],
# By default, EWS returns only the master recurring item. If you want recurring
# calendar items to be expanded, use calendar.view(start=..., end=...) instead.
start = datetime.datetime(2019, 1, 31, tzinfo=a.default_timezone)
items = a.calendar.view(
end=start + datetime.timedelta(days=1),
for item in items:
print(item.start, item.end, item.subject, item.body, item.location)
# You can combine view() with other modifiers. For example, to check for
# conflicts before adding a meeting from 8:00 to 10:00:
has_conflicts = a.calendar.view(
start=datetime.datetime(2019, 1, 31, 8, tzinfo=a.default_timezone),
end=datetime.datetime(2019, 1, 31, 10, tzinfo=a.default_timezone),
# The filtering syntax also works on collections of folders, so you can search
# multiple folders in a single request.
# Or select the folders individually
FolderCollection(account=a, folders=[a.inbox, a.calendar]).filter(subject='foo')


Paging EWS services, e.g.  FindItem  and  FindFolder , have a default page size of 100. You can change this value globally if you want:

import = 25

If you are working with very small or very large items, this may not be a reasonable value. For example, if you want to retrieve and save emails with large attachments, you can change this value on a per-queryset basis:

from exchangelib import Account
a = Account(...)
qs = a.inbox.all().only('mime_content')
qs.page_size = 5
for msg in qs:
with open('%s.eml' % msg.item_id, 'w') as f:

Finally, the bulk methods defined on the  Account  class have an optional  chunk_size  argument that you can use to set a non-default page size when fetching, creating, updating or deleting items.

from exchangelib import Account, Message
a = Account(...)
huge_list_of_items = [Message(...) for i in range(10000)]
return_ids = a.bulk_create(
folder=a.inbox, items=huge_list_of_items, chunk_size=5


The  CalendarItem  class allows you send out requests for meetings that you initiate or to cancel meetings that you already set out before. It is also possible to process  MeetingRequest  messages that are received. You can reply to these messages using the  AcceptItemTentativelyAcceptItem  and  DeclineItem  classes. If you receive a cancellation for a meeting (class  MeetingCancellation ) that you already accepted then you can also process these by removing the entry from the calendar.

import datetime
from exchangelib import Account, CalendarItem
from exchangelib.items import MeetingRequest, MeetingCancellation, \
a = Account(...)
# create a meeting request and send it out
item = CalendarItem(
start=datetime.datetime(2019, 1, 31, 8, 15, tzinfo=a.default_timezone),
end=datetime.datetime(2019, 1, 31, 8, 45, tzinfo=a.default_timezone),
subject="Subject of Meeting",
body="Please come to my meeting",
required_attendees=['', '']
# cancel a meeting that was sent out using the CalendarItem class
for calendar_item in a.calendar.all().order_by('-datetime_received')[:5]:
# only the organizer of a meeting can cancel it
    if calendar_item.organizer.email_address == a.primary_smtp_address:
# processing an incoming MeetingRequest
for item in a.inbox.all().order_by('-datetime_received')[:5]:
if isinstance(item, MeetingRequest):
item.accept(body="Sure, I'll come")
# Or:
        item.decline(body="No way!")
# Or:
# meeting requests can also be handled from the calendar - e.g. decline the
# meeting that was received last.
for calendar_item in a.calendar.all().order_by('-datetime_received')[:1]:
# processing an incoming MeetingCancellation (also delete from calendar)
for item in a.inbox.all().order_by('-datetime_received')[:5]:
if isinstance(item, MeetingCancellation):
if item.associated_calendar_item_id:
calendar_item = a.inbox.get(,


Fetching personas from a contact folder is supported using the same syntax as folders. Just start your query with  .people() :

# Navigate to a contact folder and start the search
from exchangelib import Account, DistributionList
from exchangelib.indexed_properties import EmailAddress
a = Account(...)
folder = a.root / 'AllContacts'
for p in folder.people():
for p in folder.people().only('display_name').filter(display_name='john')\
# Getting a single contact in the GAL contact list
gal = a.contacts / 'GAL Contacts'
contact = gal.get(email_addresses=EmailAddress(email=''))
# All contacts with a gmail address
gmail_contacts = list(gal.filter(
# All Gmail email addresses
gmail_addresses = [ for c in gal.filter(
) for e in c.email_addresses
# All email addresses
all_addresses = [ for c in gal.all()
for e in c.email_addresses if not isinstance(c, DistributionList)

Contact items have  photo  and  notes  fields, but they are apparently unused. Instead, you can add a contact photo and notes like this:

from exchangelib import Account, FileAttachment
a = Account(...)
contact = a.contacts.get(given_name='John')
contact.body = 'This is a note'['body'])
att = FileAttachment(
content=open('john_profile_picture.png', 'rb').read(),

Extended properties

Extended properties makes it possible to attach custom key-value pairs to items and folders on the Exchange server. There are multiple online resources that describe working with extended properties, and list many of the magic values that are used by existing Exchange clients to store common and custom properties. The following is not a comprehensive description of the possibilities, but we do intend to support all the possibilities provided by EWS.

# If folder items have extended properties, you need to register them before you
# can access them. Create a subclass of ExtendedProperty and define a set of
# matching setup values:
from exchangelib import Account, ExtendedProperty, CalendarItem, Folder, Message
a = Account(...)
class LunchMenu(ExtendedProperty):
property_set_id = '12345678-1234-1234-1234-123456781234'
property_name = 'Catering from the cafeteria'
property_type = 'String'
# Register the property on the item type of your choice
CalendarItem.register('lunch_menu', LunchMenu)
# Now your property is available as the attribute 'lunch_menu', just like any
# other attribute.
item = CalendarItem(..., lunch_menu='Foie gras et consommé de légumes')
for i in a.calendar.all():
# If you change your mind, jsut remove the property again
# You can also create named properties (e.g. created from User Defined Fields in
# Outlook, see issue #137):
class LunchMenu(ExtendedProperty):
distinguished_property_set_id = 'PublicStrings'
property_name = 'Catering from the cafeteria'
property_type = 'String'
# We support extended properties with tags. This is the definition for the
# 'completed' and 'followup' flag you can add to items in Outlook (see also
# issue #85):
class Flag(ExtendedProperty):
property_tag = 0x1090
property_type = 'Integer'
# Or with property ID:
class MyMeetingArray(ExtendedProperty):
property_set_id = '00062004-0000-0000-C000-000000000046'
property_type = 'BinaryArray'
property_id = 32852
# Or using distinguished property sets combined with property ID (here as a hex
# value to align with the format usually mentioned in Microsoft docs). This is
# the definition for a response to an Outlook Vote request (see issue #198):
class VoteResponse(ExtendedProperty):
distinguished_property_set_id = 'Common'
property_id = 0x00008524
property_type = 'String'
# Extended properties also work with folders. For folders, it's only possible to
# register custom fields on all folder types at once. This is because it's
# difficult to provide a consistent API when some folders have custom fields and
# others don't. Custom fields must be registered on the generic Folder or
# RootOfHierarchy folder classes.
# Here's an example of getting the size (in bytes) of a folder:
class FolderSize(ExtendedProperty):
property_tag = 0x0e08
property_type = 'Integer'
Folder.register('size', FolderSize)
# In general, here's how to work with any MAPI property as listed in e.g.
# Let's take `PidLidTaskDueDate` as an example. This is the due date for a
# message maked with the follow-up flag in Microsoft Outlook.
# PidLidTaskDueDate is documented at
# The property ID is `0x00008105` and the property set is `PSETID_Task`. But EWS
# wants the UUID for `PSETID_Task`, so we look that up in the MS-OXPROPS pdf:
# The UUID is `00062003-0000-0000-C000-000000000046`. The property type is
# `PT_SYSTIME` which is also called `SystemTime` (see
# )
# In conclusion, the definition for the due date becomes:

class FlagDue(ExtendedProperty):
property_set_id = '00062003-0000-0000-C000-000000000046'
property_id = 0x8105
property_type = 'SystemTime'
Message.register('flag_due', FlagDue)


# It's possible to create, delete and get attachments connected to any item
# type:
import os.path
from exchangelib import Account, FileAttachment, ItemAttachment, Message, \
CalendarItem, HTMLBody
# Process attachments on existing items. FileAttachments have a 'content'
# attribute containing the binary content of the file, and ItemAttachments have
# an 'item' attribute containing the item. The item can be a Message,
# CalendarItem, Task etc.
a = Account
for item in a.inbox.all():
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
local_path = os.path.join('/tmp',
with open(local_path, 'wb') as f:
print('Saved attachment to', local_path)
elif isinstance(attachment, ItemAttachment):
if isinstance(attachment.item, Message):
print(attachment.item.subject, attachment.item.body)
# Streaming downloads of file attachment is supported. This reduces memory
# consumption since we never store the full content of the file in-memory:
for item in a.inbox.all():
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
local_path = os.path.join('/tmp',
with open(local_path, 'wb') as f, attachment.fp as fp:
buffer =
while buffer:
buffer =
print('Saved attachment to', local_path)
# Create a new item with an attachment
item = Message(...)
# State the bytes directly, or read from file, BytesIO etc.
binary_file_content = 'Hello from unicode æøå'.encode('utf-8')
my_file = FileAttachment(name='my_file.txt', content=binary_file_content)
my_calendar_item = CalendarItem(...)
# If you got the item to attach from the server, you probably want to ignore the
# 'mime_content' field that contains copies of other field values on the item.
# This avoids duplicate attachments etc.
my_calendar_item.mime_content = None
my_appointment = ItemAttachment(name='my_appointment', item=my_calendar_item)
# Add an attachment on an existing item
my_other_file = FileAttachment(
name='my_other_file.txt', content=binary_file_content
# Remove the attachment again
# If you want to embed an image in the item body, you can link to the file in
# the HTML.
message = Message(...)
logo_filename = 'logo.png'
with open(logo_filename, 'rb') as f:
my_logo = FileAttachment(
name=logo_filename,, is_inline=True,
# Most email systems
message.body = HTMLBody(
'<html><body>Hello logo: <img src="cid:%s"></body></html>' % logo_filename
# Gmail needs this additional img attribute
message.body = HTMLBody('''\
<body>Hello logo: <img data-imagetype="AttachmentByCid" src="cid:%s"></body>
</html>''' % logo_filename
# Attachments cannot be updated via EWS. If you want to change an attachment,
# you must detach the attachment, update the relevant fields, and attach as a
# new attachment.

# Be aware that adding and deleting attachments from items that are already
# created in Exchange (items that have an item_id) will update the changekey of
# the item.

Recurring calendar items

There is full read-write support for creating recurring calendar items. You can create daily, weekly, monthly and yearly recurrences (the latter two in relative and absolute versions).

Here’s an example of creating 7 occurrences on Mondays and Wednesdays of every third week, starting September 1, 2017:

import datetime
from exchangelib import Account, CalendarItem
from exchangelib.fields import MONDAY, WEDNESDAY
from exchangelib.recurrence import Recurrence, WeeklyPattern
a = Account(...)
start = datetime.datetime(2017, 9, 1, 11, tzinfo=a.default_timezone)
end = start + datetime.timedelta(hours=2)
master_recurrence = CalendarItem(
subject='Hello Recurrence',
pattern=WeeklyPattern(interval=3, weekdays=[MONDAY, WEDNESDAY]),,
# Occurrence data for the master item
for i in a.calendar.filter(start__lt=end, end__gt=start):
print(i.subject, i.start, i.end)
for o in i.modified_occurrences:
for o in i.deleted_occurrences:
# All occurrences expanded. The recurrence will span over 4 iterations of a
# 3-week period.
for i in a.calendar.view(
start=start, end=start + datetime.timedelta(days=4*3*7)
print(i.subject, i.start, i.end)
# 'modified_occurrences' and 'deleted_occurrences' of master items are read-only
# fields. To delete or modify an occurrence, you must use 'view()' to fetch the
# occurrence and modify or delete it:
for occurrence in a.calendar.view(
start=start, end=start + datetime.timedelta(days=4*3*7)
# Delete or update random occurrences. This will affect
    # 'modified_occurrences' and  'deleted_occurrences' of the master item.
    if occurrence.start.milliseconds % 2:
# We receive timestamps as UTC but want to write back as local timezone
        occurrence.start = occurrence.start.astimezone(a.default_timezone)
occurrence.start += datetime.timedelta(minutes=30)
occurrence.end = occurrence.end.astimezone(a.default_timezone)
occurrence.end += datetime.timedelta(minutes=30)
occurrence.subject = 'My new subject'
# If you want to access a specific occurrence any you only have the master:
third_occurrence = master_recurrence.occurrence(index=3)
# Get all fields on this occurrence
# Change a field on the occurrence
third_occurrence.start += datetime.timedelta(hours=3)
# Delete occurrence['start'])
# Similarly, you can reach the master recurrence from the occurrence
master = third_occurrence.master_recurrence()
master.subject = 'An update'['subject'])

Message timestamp fields

Each  Message  item has four timestamp fields:

  • datetime_created
  • datetime_sent
  • datetime_received
  • last_modified_time

The values for these fields are set by the Exchange server and are not modifiable via EWS. All values are timezone-aware  EWSDateTime  instances.

The  datetime_sent  value may be earlier than  datetime_created .

Out of Facility (OOF)

You can get and set OOF messages using the  Account.oof_settings  property:

import datetime
from exchangelib import Account, OofSettings
a = Account(...)
# Get the current OOF settings
# Change the OOF settings to something else
a.oof_settings = OofSettings(
internal_reply="I'm in the pub. See ya guys!",
external_reply="I'm having a business dinner in town",
start=datetime.datetime(2017, 11, 1, 11, tzinfo=a.default_timezone),
end=datetime.datetime(2017, 12, 1, 11, tzinfo=a.default_timezone),
# Disable OOF messages
a.oof_settings = OofSettings(

Mail tips

Mail tips for an account contain some extra information about the account, e.g. OOF information, max message size, whether the mailbox is full, messages are moderated etc. Here’s how to get mail tips for a single account:

from exchangelib import Account
a = Account(...)

Delegate information

An account can have delegates, which are other users that are allowed to access the account. Here’s how to fetch information about those delegates, including which level of access they have to the account.

from exchangelib import Account
a = Account(...)

Export and upload

Exchange supports backup and restore of folder contents using special export and upload services. They are available on the  Account  model:

from exchangelib import Account
a = Account(...)
items = a.inbox.all().only('id', 'changekey')
data = a.export(items)  # Pass a list of Items or (item_id, changekey) tuples
a.upload((a.inbox, d) for d in data)  # Expects a list of (folder, data) tuples

Synchronization, subscriptions and notifications

Methods for synchronization of folders and items, and for subscribing to, and receiving notifications, are available on the  Folder model. An in-depth description of how to synchronize folders and items using EWS is available at A description of how to subscribe to notifications and receive notifications using EWS is available at

from exchangelib import Account
from import CopiedEvent, CreatedEvent, DeletedEvent, \
ModifiedEvent, MovedEvent, NewMailEvent, StatusEvent, FreeBusyChangedEvent
a = Account(...)
# Synchronize your local folder hierarchy underneath a.inbox
for change_type, item in a.inbox.sync_hierarchy():
# Do something depending on the change types defined in
    # SyncFolderHierarchy.CHANGE_TYPES
# The next time you call a.inbox.sync_hierarchy(), you will only get folder
# changes since the last .sync_hierarchy() call.

# Synchronize your local items within a.inbox
for change_type, item in a.inbox.sync_items():
# Do something depending on the change types defined in
    # SyncFolderItems.CHANGE_TYPES
# The next time you call a.inbox.sync_items(), you will only get item changes
# since the last .sync_items() call.

# Create a pull subscription that can be used to pull events from the server
subscription_id, watermark = a.inbox.subscribe_to_pull()
# Create a push subscription. The server will regularly send a request to the
# callback URL to deliver changes or a status message.
subscription_id, watermark = a.inbox.subscribe_to_push(
# Create a streaming subscription that can be used to stream events from the
# server.
subscription_id = a.inbox.subscribe_to_streaming()
# Cancel the subscription. Does not apply to push subscriptions that cancel
# automatically after a certain amount of failed attempts.
# Pull events from the server. This method returns Notification objects that
# contain events in the 'events' attribute and a new watermark in the
# 'watermark' attribute.
for notification in a.inbox.get_events(subscription_id, watermark):
for event in
if isinstance(event, (CreatedEvent, ModifiedEvent)):
# Do something
elif isinstance(event, (CopiedEvent, DeletedEvent)):
# Do something else
# Stream events from the server. This method returns Notification objects that
# contain events in the 'events' attribute. Takes an optional
# 'connection_timeout' argument that defines how long, in minutes, to keep the
# connection open. .get_streaming_events() will block while the connection is
# open, yielding notifications as they become available on the request stream.
for notification in a.inbox.get_streaming_events(
subscription_id, connection_timeout=1
for event in
if isinstance(event, (MovedEvent, NewMailEvent)):
# Do something
elif isinstance(event, (StatusEvent, FreeBusyChangedEvent)):
# Do something else

Non-account services

from exchangelib import Account, DLMailbox
from import AlternateId, EWS_ID, OWA_ID
a = Account(...)
# Get timezone information from the server
# Get room lists defined on the server
# Get rooms belonging to a specific room list
for rl in a.protocol.get_roomlists():
# Get account information for a list of names or email addresses
for mailbox in a.protocol.resolve_names(['', '']):
for mailbox, contact in a.protocol.resolve_names(
['anne', 'bart'], return_full_contact_data=True
print(mailbox.email_address, contact.display_name)
# Get all mailboxes on a distribution list
for mailbox in a.protocol.expand_dl(
DLMailbox(email_address='', mailbox_type='PublicDL')
# Or just pass a string containing the SMTP address
for mailbox in a.protocol.expand_dl(''):
# Convert item IDs from one format to another
for converted_id in a.protocol.convert_ids([
AlternateId(id='AAA=', format=EWS_ID, mailbox=a.primary_smtp_address),
], destination_format=OWA_ID):
# Get searchable mailboxes. This method is only available to users who have been
# assigned the Discovery Management RBAC role. (This feature works on Exchange
# 2013 onwards)
for mailbox in a.protocol.get_searchable_mailboxes():

EWS supports getting availability information for a set of users in a certain timeframe. The server returns an object for each account containing free/busy information, including a list of calendar events in the user’s calendar, and the working hours and timezone of the user.

import datetime
from exchangelib import Account
a = Account(...)
start =
end = start + datetime.timedelta(hours=6)
accounts = [(a, 'Organizer', False)]
for busy_info in a.protocol.get_free_busy_info(
accounts=accounts, start=start, end=end

The calendar events and working hours are returned as naive datetimes. To convert to timezone-aware datetimes, a bit of extra work is needed if the users are not known to be in the same timezone.

# Get all server timezones. We need that to convert 'working_hours_timezone'
import datetime
from exchangelib import Account, EWSTimeZone
a = Account(...)
timezones = list(a.protocol.get_timezones(return_full_timezone_data=True))
# Get availability information for a list of accounts
start =
end = start + datetime.timedelta(hours=6)
# get_free_busy_info expects (account, attendee_type, exclude_conflicts) tuples
accounts = [(a, 'Organizer', False)]
for busy_info in a.protocol.get_free_busy_info(
accounts=accounts, start=start, end=end
# Convert the TimeZone object to a Microsoft timezone ID
    ms_id = busy_info.working_hours_timezone.to_server_timezone(
timezones, start.year
account_tz = EWSTimeZone.from_ms_id(ms_id)
print(account_tz, busy_info.working_hours)
for event in busy_info.calendar_events:
print(account_tz.localize(event.start), account_tz.localize(event.end))


If you are having trouble using this library, the first thing to try is to enable debug logging. This will output a huge amount of information about what is going on, most notable the actual XML documents that are going over the wire. This can be really handy to see which fields are being sent and received.

import logging
# This handler will pretty-print and syntax highlight the request and response
# XML documents
from exchangelib.util import PrettyXmlHandler
logging.basicConfig(level=logging.DEBUG, handlers=[PrettyXmlHandler()])
# Your code using exchangelib goes here

Most class definitions have a docstring containing at least a URL to the MSDN page for the corresponding XML element.

from exchangelib import CalendarItem


The test suite is split into unit tests, and integration tests that require a real Exchange server. If you want to run the full test suite, you must provide setup parameters for a test account. Copy  settings.yml.sample  to  settings.yml  and change the default parameters. If a  settings.yml  is available, we will run the entire test suite. Otherwise, just the unit tests are run.

WARNING: The test account should not contain valuable data. The tests try hard to no touch existing data in the account, but accidents happen.

You can run either the entire test suite or individual tests.

# Full test suite
python -m unittest
# Single test class or test case
python -m unittest -k test_folder.FolderTest.test_refresh
# If you want extreme levels of debug output:
DEBUG=1 python -m unittest -k test_folder.FolderTest.test_refresh
# Tests can be run in parallel if you install the 'unittest-parallel' package
unittest-parallel -j 4



0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x
error: Alert: Content is protected !!