0
# exchangelib
1
2
A comprehensive Python client library for Microsoft Exchange Web Services (EWS) that provides a Django-style ORM interface for Exchange mailboxes. It enables platform-independent access to on-premise Microsoft Exchange 2007-2016 servers and Office365, offering well-documented and well-tested functionality for searching, creating, updating, deleting, exporting and uploading calendar, mailbox, task, contact and distribution list items.
3
4
## Package Information
5
6
- **Package Name**: exchangelib
7
- **Language**: Python
8
- **Installation**: `pip install exchangelib`
9
- **PyPI**: https://pypi.org/project/exchangelib/
10
- **Documentation**: https://ecederstrand.github.io/exchangelib/
11
12
## Core Imports
13
14
```python
15
from exchangelib import Account, Credentials, Configuration, DELEGATE, IMPERSONATION
16
```
17
18
For specific functionality:
19
20
```python
21
from exchangelib import (
22
# Core account and authentication
23
Account, Credentials, OAuth2Credentials, OAuth2AuthorizationCodeCredentials,
24
OAuth2LegacyCredentials, Configuration, O365InteractiveConfiguration, Identity,
25
26
# Exchange items
27
Message, CalendarItem, Contact, Task, DistributionList,
28
29
# Response items
30
AcceptItem, DeclineItem, TentativelyAcceptItem, CancelCalendarItem,
31
ForwardItem, ReplyToItem, ReplyAllToItem, PostItem, PostReplyItem,
32
33
# Date/time handling
34
EWSDateTime, EWSDate, EWSTimeZone, UTC, UTC_NOW,
35
36
# Properties
37
Mailbox, DLMailbox, Attendee, Body, HTMLBody, ItemId, UID, Room, RoomList,
38
39
# Folders and querying
40
Folder, FolderCollection, RootOfHierarchy, Q,
41
42
# Extended properties and settings
43
ExtendedProperty, OofSettings,
44
45
# Protocol and transport
46
BaseProtocol, Version, Build, FailFast, FaultTolerance, TLSClientAuth, NoVerifyHTTPAdapter,
47
48
# Authentication constants
49
BASIC, CBA, DIGEST, GSSAPI, NTLM, OAUTH2, SSPI,
50
51
# Access type constants
52
DELEGATE, IMPERSONATION,
53
54
# Folder depth constants
55
DEEP, SHALLOW,
56
57
# Functions
58
discover, close_connections, __version__
59
)
60
```
61
62
## Basic Usage
63
64
```python
65
from exchangelib import Account, Credentials, DELEGATE
66
67
# Basic authentication setup
68
credentials = Credentials(username='myuser@example.com', password='mypassword')
69
account = Account(
70
primary_smtp_address='myuser@example.com',
71
credentials=credentials,
72
autodiscover=True,
73
access_type=DELEGATE
74
)
75
76
# Access mailbox folders
77
inbox = account.inbox
78
sent = account.sent
79
calendar = account.calendar
80
81
# Read recent emails
82
for item in inbox.all().order_by('-datetime_received')[:10]:
83
print(f"From: {item.sender}")
84
print(f"Subject: {item.subject}")
85
print(f"Received: {item.datetime_received}")
86
87
# Send a message
88
from exchangelib import Message, Mailbox, HTMLBody
89
90
message = Message(
91
account=account,
92
folder=account.sent,
93
subject='Test Email',
94
body=HTMLBody('<h1>Hello from exchangelib!</h1>'),
95
to_recipients=[Mailbox(email_address='recipient@example.com')]
96
)
97
message.send_and_save()
98
99
# Create a calendar appointment
100
from exchangelib import CalendarItem, EWSDateTime
101
from datetime import datetime, timedelta
102
103
start_time = EWSDateTime.from_datetime(datetime.now() + timedelta(days=1))
104
end_time = start_time + timedelta(hours=1)
105
106
appointment = CalendarItem(
107
account=account,
108
folder=account.calendar,
109
subject='Team Meeting',
110
body='Weekly team sync meeting',
111
start=start_time,
112
end=end_time
113
)
114
appointment.save()
115
```
116
117
## Architecture
118
119
The exchangelib architecture follows a Django-ORM inspired design:
120
121
- **Account**: Central interface representing an Exchange mailbox with access to folders and services
122
- **Folders**: Container objects (Inbox, Calendar, Contacts) that hold and manage Exchange items
123
- **Items**: Exchange objects (Message, CalendarItem, Contact, Task) with full CRUD operations
124
- **Properties**: Data structures representing Exchange properties (Mailbox, Attendee, Body)
125
- **Services**: Low-level EWS operations for advanced functionality
126
- **Authentication**: Multiple authentication methods including Basic, NTLM, OAuth2, and certificates
127
128
This design provides a high-level, intuitive interface while maintaining access to the full power of Exchange Web Services.
129
130
## Capabilities
131
132
### Account Management and Authentication
133
134
Core functionality for connecting to Exchange servers with support for multiple authentication methods, autodiscovery, and account configuration. Includes support for both on-premise Exchange and Office365.
135
136
```python { .api }
137
class Account:
138
def __init__(
139
self,
140
primary_smtp_address: str,
141
fullname: str = None,
142
access_type: str = None,
143
autodiscover: bool = False,
144
credentials: Credentials = None,
145
config: Configuration = None,
146
locale: str = None,
147
default_timezone: EWSTimeZone = None
148
): ...
149
150
class Credentials:
151
def __init__(self, username: str, password: str): ...
152
153
class OAuth2Credentials:
154
def __init__(
155
self,
156
client_id: str,
157
client_secret: str,
158
tenant_id: str = None,
159
identity: Identity = None,
160
access_token: dict = None
161
): ...
162
163
class OAuth2AuthorizationCodeCredentials:
164
def __init__(
165
self,
166
client_id: str,
167
client_secret: str,
168
tenant_id: str = None,
169
identity: Identity = None,
170
access_token: dict = None
171
): ...
172
173
class OAuth2LegacyCredentials:
174
def __init__(
175
self,
176
client_id: str,
177
client_secret: str,
178
tenant_id: str = None,
179
identity: Identity = None,
180
access_token: dict = None
181
): ...
182
183
class Identity:
184
def __init__(
185
self,
186
primary_smtp_address: str = None,
187
name: str = None,
188
sid: str = None,
189
upn: str = None
190
): ...
191
192
class Configuration:
193
def __init__(
194
self,
195
service_endpoint: str = None,
196
credentials: Credentials = None,
197
auth_type: str = None,
198
version: Version = None,
199
retry_policy: str = None
200
): ...
201
202
class O365InteractiveConfiguration:
203
def __init__(
204
self,
205
client_id: str,
206
username: str = None
207
): ...
208
```
209
210
[Account and Authentication](./account-auth.md)
211
212
### Message Operations
213
214
Complete email functionality including sending, receiving, replying, forwarding, and managing email messages. Supports both plain text and HTML content, attachments, and advanced email features.
215
216
```python { .api }
217
class Message:
218
def send(self): ...
219
def send_and_save(self): ...
220
def reply(self, subject: str = None, body: str = None): ...
221
def reply_all(self, subject: str = None, body: str = None): ...
222
def forward(self, subject: str = None, body: str = None): ...
223
224
def bulk_create(items: list[Message]): ...
225
def bulk_update(items: list[Message]): ...
226
def bulk_delete(items: list[Message]): ...
227
```
228
229
[Messages and Email](./messages.md)
230
231
### Calendar Operations
232
233
Full calendar functionality for creating, updating, and managing appointments, meetings, and recurring events. Includes support for attendees, meeting requests, and complex recurrence patterns.
234
235
```python { .api }
236
class CalendarItem:
237
def accept(self): ...
238
def decline(self): ...
239
def tentatively_accept(self): ...
240
def cancel(self): ...
241
242
class Attendee:
243
def __init__(
244
self,
245
mailbox: Mailbox,
246
response_type: str = None
247
): ...
248
```
249
250
[Calendar and Appointments](./calendar.md)
251
252
### Contacts and Distribution Lists
253
254
Contact management functionality for creating, updating, and organizing contact information. Includes support for distribution lists and contact groups.
255
256
```python { .api }
257
class Contact:
258
def save(self): ...
259
def delete(self): ...
260
261
class DistributionList:
262
def expand(self): ...
263
```
264
265
[Contacts and Distribution Lists](./contacts.md)
266
267
### Tasks and To-Do Items
268
269
Task management functionality for creating, updating, and tracking tasks and to-do items with support for due dates, priorities, and completion status.
270
271
```python { .api }
272
class Task:
273
def save(self): ...
274
def delete(self): ...
275
```
276
277
[Tasks](./tasks.md)
278
279
### Folder Operations and Organization
280
281
Folder management for organizing and accessing Exchange folders, including standard folders (Inbox, Sent, Calendar) and custom folders. Supports folder creation, deletion, and hierarchical organization.
282
283
```python { .api }
284
class Folder:
285
def create_folder(self, name: str): ...
286
def delete_folder(self): ...
287
def get_folder(self, name: str): ...
288
289
class FolderCollection:
290
def filter(self, **kwargs): ...
291
def all(self): ...
292
```
293
294
[Folders and Organization](./folders.md)
295
296
### Search and Filtering
297
298
Advanced search and filtering capabilities using Django-style query syntax. Supports complex queries across all Exchange item types with efficient server-side filtering.
299
300
```python { .api }
301
class Q:
302
def __init__(self, **kwargs): ...
303
def __and__(self, other): ...
304
def __or__(self, other): ...
305
def __invert__(self): ...
306
307
def filter(self, *args, **kwargs): ...
308
def exclude(self, *args, **kwargs): ...
309
def order_by(self, *fields): ...
310
```
311
312
[Search and Filtering](./search.md)
313
314
### Attachments and File Handling
315
316
Comprehensive attachment support for both file attachments and embedded item attachments. Includes functionality for uploading, downloading, and managing attachments across all Exchange item types.
317
318
```python { .api }
319
class FileAttachment:
320
def save(self, path: str): ...
321
322
class ItemAttachment:
323
def save(self): ...
324
```
325
326
[Attachments](./attachments.md)
327
328
### Date and Time Handling
329
330
Specialized date and time functionality designed for Exchange compatibility, including timezone handling, UTC conversion, and Exchange-specific datetime formats.
331
332
```python { .api }
333
class EWSDateTime:
334
@classmethod
335
def from_datetime(cls, dt: datetime): ...
336
def to_timezone(self, tz: EWSTimeZone): ...
337
338
class EWSTimeZone:
339
@classmethod
340
def from_pytz(cls, tz): ...
341
```
342
343
[Date and Time](./datetime.md)
344
345
### Advanced Features
346
347
Advanced functionality including bulk operations, extended properties, impersonation, and low-level EWS service access for complex Exchange operations.
348
349
```python { .api }
350
def bulk_create(items: list): ...
351
def bulk_update(items: list): ...
352
def bulk_delete(items: list): ...
353
354
class ExtendedProperty:
355
def __init__(self, distinguished_property_set_id: str, property_name: str, property_type: str): ...
356
```
357
358
[Advanced Features](./advanced.md)
359
360
## Types
361
362
```python { .api }
363
# Core types
364
class Account: ...
365
class Credentials: ...
366
class Configuration: ...
367
368
# Exchange items
369
class Message: ...
370
class CalendarItem: ...
371
class Contact: ...
372
class Task: ...
373
class DistributionList: ...
374
375
# Properties
376
class Mailbox: ...
377
class Attendee: ...
378
class Body: ...
379
class HTMLBody: ...
380
class ItemId: ...
381
382
# Folders
383
class Folder: ...
384
class FolderCollection: ...
385
386
# Date/time
387
class EWSDateTime: ...
388
class EWSDate: ...
389
class EWSTimeZone: ...
390
391
# Attachments
392
class FileAttachment: ...
393
class ItemAttachment: ...
394
395
# Extended properties
396
class ExtendedProperty: ...
397
398
# Query objects
399
class Q: ...
400
401
# Constants
402
DELEGATE: str
403
IMPERSONATION: str
404
DEEP: str
405
SHALLOW: str
406
```