class Attachment
Represents a file or item (contact, event, or message) attached to an event or message in Office 365, providing methods to download and access attachment content and metadata.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/outlook/mail/attachments/attachment.py
11 - 75
moderate
Purpose
The Attachment class is a specialized Entity that manages file and item attachments in Office 365 services. It provides functionality to download attachment content, retrieve raw attachment data, and access attachment metadata such as name, content type, size, and last modified date. This class is typically used when working with email attachments, calendar event attachments, or message attachments in Microsoft Graph API integrations.
Source Code
class Attachment(Entity):
"""A file or item (contact, event or message) attached to an event or message."""
def __repr__(self):
return self.name or self.id
def download(self, file_object):
# type: (IO) -> Self
"""Downloads raw contents of a file or item attachment"""
def _save_content(return_type):
# type: (ClientResult[AnyStr]) -> None
file_object.write(return_type.value)
self.get_content().after_execute(_save_content)
return self
def get_content(self):
# type: () -> ClientResult[AnyStr]
"""Gets the raw contents of a file or item attachment"""
return_type = ClientResult(self.context)
qry = FunctionQuery(self, "$value", None, return_type)
self.context.add_query(qry)
return return_type
@property
def name(self):
# type: () -> Optional[str]
"""The attachment's file name."""
return self.properties.get("name", None)
@name.setter
def name(self, value):
# type: (str) -> None
"""Sets the attachment's file name."""
self.set_property("name", value)
@property
def content_type(self):
# type: () -> Optional[str]
return self.properties.get("contentType", None)
@content_type.setter
def content_type(self, value):
# type: (str) -> None
self.set_property("contentType", value)
@property
def size(self):
# type: () -> Optional[int]
return self.properties.get("size", None)
@property
def last_modified_datetime(self):
# type: () -> Optional[datetime.datetime]
"""The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time."""
return self.properties.get("lastModifiedDateTime", datetime.datetime.min)
def get_property(self, name, default_value=None):
if default_value is None:
property_mapping = {
"lastModifiedDateTime": self.last_modified_datetime,
}
default_value = property_mapping.get(name, None)
return super(Attachment, self).get_property(name, default_value)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
Entity | - |
Parameter Details
__init__: Inherits from Entity class. Constructor parameters are not explicitly defined in this class but are inherited from the Entity base class. Typically initialized through Office 365 API responses rather than direct instantiation.
Return Value
Instantiation returns an Attachment object. The download() method returns Self (the Attachment instance) for method chaining. The get_content() method returns a ClientResult[AnyStr] containing the raw attachment content. Properties return their respective types: name and content_type return Optional[str], size returns Optional[int], and last_modified_datetime returns Optional[datetime.datetime].
Class Interface
Methods
__repr__(self) -> str
Purpose: Returns a string representation of the attachment, using the name if available, otherwise the ID
Returns: String representation of the attachment (name or ID)
download(self, file_object: IO) -> Self
Purpose: Downloads the raw contents of a file or item attachment to a provided file object
Parameters:
file_object: A file-like object (IO) where the attachment content will be written
Returns: Returns self (the Attachment instance) for method chaining
get_content(self) -> ClientResult[AnyStr]
Purpose: Gets the raw contents of a file or item attachment as a ClientResult object
Returns: ClientResult[AnyStr] containing the raw attachment content that will be populated after execute_query()
get_property(self, name: str, default_value=None) -> Any
Purpose: Retrieves a property value with special handling for lastModifiedDateTime mapping
Parameters:
name: The property name to retrievedefault_value: Default value to return if property is not found
Returns: The property value or default_value if not found
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
name |
Optional[str] | The attachment's file name. Can be read and written. | instance |
content_type |
Optional[str] | The MIME content type of the attachment (e.g., 'application/pdf', 'image/jpeg'). Can be read and written. | instance |
size |
Optional[int] | The size of the attachment in bytes. Read-only property. | instance |
last_modified_datetime |
Optional[datetime.datetime] | The timestamp when the attachment was last modified, in ISO 8601 format and UTC time. Returns datetime.datetime.min if not set. Read-only property. | instance |
properties |
dict | Inherited from Entity. Dictionary storing all attachment properties retrieved from the API. | instance |
context |
ClientContext | Inherited from Entity. The Office 365 client context used for API operations. | instance |
id |
str | Inherited from Entity. The unique identifier of the attachment. | instance |
Dependencies
datetimetypingtyping_extensionsoffice365
Required Imports
import datetime
from typing import IO, AnyStr, Optional
from typing_extensions import Self
from office365.entity import Entity
from office365.runtime.client_result import ClientResult
from office365.runtime.queries.function import FunctionQuery
Usage Example
# Assuming you have an authenticated Office 365 context and a message object
from office365.outlook.mail.messages.message import Message
import io
# Get a message with attachments
message = mailbox.messages.get_by_id('message_id')
message.get().execute_query()
# Access attachments
for attachment in message.attachments:
print(f"Attachment name: {attachment.name}")
print(f"Content type: {attachment.content_type}")
print(f"Size: {attachment.size} bytes")
print(f"Last modified: {attachment.last_modified_datetime}")
# Download attachment to a file
with open(attachment.name, 'wb') as file_obj:
attachment.download(file_obj)
context.execute_query()
# Or get content directly
content_result = attachment.get_content()
context.execute_query()
raw_content = content_result.value
Best Practices
- Always call context.execute_query() after download() or get_content() to actually execute the API request
- Use download() with a file object for large attachments to avoid loading entire content into memory
- Check attachment.size before downloading to handle large files appropriately
- The download() method returns self for method chaining but requires execute_query() to complete
- Properties are lazily loaded from the properties dictionary; ensure the attachment object is fully loaded before accessing properties
- The last_modified_datetime property returns datetime.datetime.min as default if not set
- Use get_content() when you need the raw bytes in memory; use download() when writing directly to a file
- The __repr__ method returns the attachment name or ID for easy debugging and logging
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class FileAttachment 83.1% similar
-
class ItemAttachment 78.7% similar
-
class AttachmentItem 76.6% similar
-
class AttachmentBase 74.2% similar
-
class TaskFileAttachment 71.5% similar