Client for Microsoft Exchange Web Services (EWS) providing Django-style ORM interface for Exchange mailboxes.
npx @tessl/cli install tessl/pypi-exchangelib@5.5.0A 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.
pip install exchangelibfrom exchangelib import Account, Credentials, Configuration, DELEGATE, IMPERSONATIONFor specific functionality:
from exchangelib import (
# Core account and authentication
Account, Credentials, OAuth2Credentials, OAuth2AuthorizationCodeCredentials,
OAuth2LegacyCredentials, Configuration, O365InteractiveConfiguration, Identity,
# Exchange items
Message, CalendarItem, Contact, Task, DistributionList,
# Response items
AcceptItem, DeclineItem, TentativelyAcceptItem, CancelCalendarItem,
ForwardItem, ReplyToItem, ReplyAllToItem, PostItem, PostReplyItem,
# Date/time handling
EWSDateTime, EWSDate, EWSTimeZone, UTC, UTC_NOW,
# Properties
Mailbox, DLMailbox, Attendee, Body, HTMLBody, ItemId, UID, Room, RoomList,
# Folders and querying
Folder, FolderCollection, RootOfHierarchy, Q,
# Extended properties and settings
ExtendedProperty, OofSettings,
# Protocol and transport
BaseProtocol, Version, Build, FailFast, FaultTolerance, TLSClientAuth, NoVerifyHTTPAdapter,
# Authentication constants
BASIC, CBA, DIGEST, GSSAPI, NTLM, OAUTH2, SSPI,
# Access type constants
DELEGATE, IMPERSONATION,
# Folder depth constants
DEEP, SHALLOW,
# Functions
discover, close_connections, __version__
)from exchangelib import Account, Credentials, DELEGATE
# Basic authentication setup
credentials = Credentials(username='myuser@example.com', password='mypassword')
account = Account(
primary_smtp_address='myuser@example.com',
credentials=credentials,
autodiscover=True,
access_type=DELEGATE
)
# Access mailbox folders
inbox = account.inbox
sent = account.sent
calendar = account.calendar
# Read recent emails
for item in inbox.all().order_by('-datetime_received')[:10]:
print(f"From: {item.sender}")
print(f"Subject: {item.subject}")
print(f"Received: {item.datetime_received}")
# Send a message
from exchangelib import Message, Mailbox, HTMLBody
message = Message(
account=account,
folder=account.sent,
subject='Test Email',
body=HTMLBody('<h1>Hello from exchangelib!</h1>'),
to_recipients=[Mailbox(email_address='recipient@example.com')]
)
message.send_and_save()
# Create a calendar appointment
from exchangelib import CalendarItem, EWSDateTime
from datetime import datetime, timedelta
start_time = EWSDateTime.from_datetime(datetime.now() + timedelta(days=1))
end_time = start_time + timedelta(hours=1)
appointment = CalendarItem(
account=account,
folder=account.calendar,
subject='Team Meeting',
body='Weekly team sync meeting',
start=start_time,
end=end_time
)
appointment.save()The exchangelib architecture follows a Django-ORM inspired design:
This design provides a high-level, intuitive interface while maintaining access to the full power of Exchange Web Services.
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.
class Account:
def __init__(
self,
primary_smtp_address: str,
fullname: str = None,
access_type: str = None,
autodiscover: bool = False,
credentials: Credentials = None,
config: Configuration = None,
locale: str = None,
default_timezone: EWSTimeZone = None
): ...
class Credentials:
def __init__(self, username: str, password: str): ...
class OAuth2Credentials:
def __init__(
self,
client_id: str,
client_secret: str,
tenant_id: str = None,
identity: Identity = None,
access_token: dict = None
): ...
class OAuth2AuthorizationCodeCredentials:
def __init__(
self,
client_id: str,
client_secret: str,
tenant_id: str = None,
identity: Identity = None,
access_token: dict = None
): ...
class OAuth2LegacyCredentials:
def __init__(
self,
client_id: str,
client_secret: str,
tenant_id: str = None,
identity: Identity = None,
access_token: dict = None
): ...
class Identity:
def __init__(
self,
primary_smtp_address: str = None,
name: str = None,
sid: str = None,
upn: str = None
): ...
class Configuration:
def __init__(
self,
service_endpoint: str = None,
credentials: Credentials = None,
auth_type: str = None,
version: Version = None,
retry_policy: str = None
): ...
class O365InteractiveConfiguration:
def __init__(
self,
client_id: str,
username: str = None
): ...Complete email functionality including sending, receiving, replying, forwarding, and managing email messages. Supports both plain text and HTML content, attachments, and advanced email features.
class Message:
def send(self): ...
def send_and_save(self): ...
def reply(self, subject: str = None, body: str = None): ...
def reply_all(self, subject: str = None, body: str = None): ...
def forward(self, subject: str = None, body: str = None): ...
def bulk_create(items: list[Message]): ...
def bulk_update(items: list[Message]): ...
def bulk_delete(items: list[Message]): ...Full calendar functionality for creating, updating, and managing appointments, meetings, and recurring events. Includes support for attendees, meeting requests, and complex recurrence patterns.
class CalendarItem:
def accept(self): ...
def decline(self): ...
def tentatively_accept(self): ...
def cancel(self): ...
class Attendee:
def __init__(
self,
mailbox: Mailbox,
response_type: str = None
): ...Contact management functionality for creating, updating, and organizing contact information. Includes support for distribution lists and contact groups.
class Contact:
def save(self): ...
def delete(self): ...
class DistributionList:
def expand(self): ...Contacts and Distribution Lists
Task management functionality for creating, updating, and tracking tasks and to-do items with support for due dates, priorities, and completion status.
class Task:
def save(self): ...
def delete(self): ...Folder management for organizing and accessing Exchange folders, including standard folders (Inbox, Sent, Calendar) and custom folders. Supports folder creation, deletion, and hierarchical organization.
class Folder:
def create_folder(self, name: str): ...
def delete_folder(self): ...
def get_folder(self, name: str): ...
class FolderCollection:
def filter(self, **kwargs): ...
def all(self): ...Advanced search and filtering capabilities using Django-style query syntax. Supports complex queries across all Exchange item types with efficient server-side filtering.
class Q:
def __init__(self, **kwargs): ...
def __and__(self, other): ...
def __or__(self, other): ...
def __invert__(self): ...
def filter(self, *args, **kwargs): ...
def exclude(self, *args, **kwargs): ...
def order_by(self, *fields): ...Comprehensive attachment support for both file attachments and embedded item attachments. Includes functionality for uploading, downloading, and managing attachments across all Exchange item types.
class FileAttachment:
def save(self, path: str): ...
class ItemAttachment:
def save(self): ...Specialized date and time functionality designed for Exchange compatibility, including timezone handling, UTC conversion, and Exchange-specific datetime formats.
class EWSDateTime:
@classmethod
def from_datetime(cls, dt: datetime): ...
def to_timezone(self, tz: EWSTimeZone): ...
class EWSTimeZone:
@classmethod
def from_pytz(cls, tz): ...Advanced functionality including bulk operations, extended properties, impersonation, and low-level EWS service access for complex Exchange operations.
def bulk_create(items: list): ...
def bulk_update(items: list): ...
def bulk_delete(items: list): ...
class ExtendedProperty:
def __init__(self, distinguished_property_set_id: str, property_name: str, property_type: str): ...# Core types
class Account: ...
class Credentials: ...
class Configuration: ...
# Exchange items
class Message: ...
class CalendarItem: ...
class Contact: ...
class Task: ...
class DistributionList: ...
# Properties
class Mailbox: ...
class Attendee: ...
class Body: ...
class HTMLBody: ...
class ItemId: ...
# Folders
class Folder: ...
class FolderCollection: ...
# Date/time
class EWSDateTime: ...
class EWSDate: ...
class EWSTimeZone: ...
# Attachments
class FileAttachment: ...
class ItemAttachment: ...
# Extended properties
class ExtendedProperty: ...
# Query objects
class Q: ...
# Constants
DELEGATE: str
IMPERSONATION: str
DEEP: str
SHALLOW: str