Client for Microsoft Exchange Web Services (EWS) providing Django-style ORM interface for Exchange mailboxes.
—
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 __init__(
self,
name: str = None,
content: bytes = None,
content_type: str = None,
content_id: str = None,
content_location: str = None,
is_inline: bool = False
):
"""Create a file attachment."""
name: str
content: bytes
content_type: str
content_id: str
size: int
last_modified_time: EWSDateTime
is_inline: bool
def save(self, path: str):
"""Save attachment to file system."""
@classmethod
def from_file(cls, path: str, name: str = None) -> FileAttachment:
"""Create attachment from file."""class ItemAttachment:
def __init__(self, name: str = None, item: Item = None):
"""Create an item attachment."""
name: str
item: Item
size: int
last_modified_time: EWSDateTime
def save(self):
"""Save the attached item."""class Item:
attachments: list[FileAttachment | ItemAttachment]
has_attachments: bool
def attach(self, attachment: FileAttachment | ItemAttachment):
"""Add an attachment to the item."""
def detach(self, attachment: FileAttachment | ItemAttachment):
"""Remove an attachment from the item."""Usage examples:
from exchangelib import FileAttachment, ItemAttachment, Message
# Create message with file attachment
message = Message(
account=account,
subject='Document for Review',
body=Body('Please review the attached document.'),
to_recipients=[Mailbox(email_address='reviewer@company.com')]
)
# Add file attachment
attachment = FileAttachment.from_file('/path/to/document.pdf', 'Document.pdf')
message.attachments.append(attachment)
message.save()
# Download attachments from received message
for item in account.inbox.filter(has_attachments=True):
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
attachment.save(f'/downloads/{attachment.name}')
# Attach another email as item attachment
item_attachment = ItemAttachment(
name='Referenced Email',
item=referenced_message
)
message.attachments.append(item_attachment)Install with Tessl CLI
npx tessl i tessl/pypi-exchangelib