class MailFolder
Represents a mail folder in a user's mailbox (e.g., Inbox, Drafts) that can contain messages, Outlook items, and child folders. Provides methods for folder operations like copying, emptying, and marking messages as read/unread.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/outlook/mail/folders/folder.py
15 - 178
moderate
Purpose
This class models a Microsoft Outlook/Exchange mail folder entity, providing a comprehensive interface for managing email folders. It supports hierarchical folder structures with child folders, message collections, and extended properties. Key functionality includes copying folders, bulk operations on messages (empty, mark all as read/unread), and access to folder metadata like item counts and display names. The class inherits from Entity and integrates with the Office365 API context for executing operations.
Source Code
class MailFolder(Entity):
"""A mail folder in a user's mailbox, such as Inbox and Drafts. Mail folders can contain messages,
other Outlook items, and child mail folders."""
def copy(self, destination_id):
"""
Copy a mailfolder and its contents to another mailfolder.
:param str destination_id: The folder ID, or a well-known folder name. For a list of supported well-known folder
names, see mailFolder resource type.
"""
return_type = MailFolder(self.context)
payload = {"DestinationId": destination_id}
qry = ServiceOperationQuery(self, "copy", None, payload, None, return_type)
self.context.add_query(qry)
return return_type
def empty(self, delete_sub_folders=False):
"""
Empties the folder
:param bool delete_sub_folders: true to indicate that subfolders should also be deleted; otherwise, false.
"""
def _empty(col):
# type: (MessageCollection) -> None
if not col.has_next:
[m.delete_object() for m in col]
self.messages.get_all(page_loaded=_empty)
return self
def mark_all_items_as_read(self):
"""Marks all items in folder as read."""
def _mark_all_items_as_read(col):
# type: (MessageCollection) -> None
[m.set_property("isRead", True).update() for m in col.current_page]
self.messages.get_all(1, page_loaded=_mark_all_items_as_read)
return self
def mark_all_items_as_unread(self):
"""Marks all items in folder as unread."""
def _mark_all_items_as_unread(col):
# type: (MessageCollection) -> None
[m.set_property("isRead", False).update() for m in col.current_page]
self.messages.get_all(page_loaded=_mark_all_items_as_unread)
return self
@property
def child_folder_count(self):
# type: () -> Optional[int]
"""The number of immediate child mailFolders in the current mailFolder."""
return self.properties.get("childFolderCount", None)
@property
def display_name(self):
# type: () -> Optional[str]
"""The name of the Mail folder"""
return self.properties.get("displayName", None)
@property
def is_hidden(self):
# type: () -> Optional[bool]
"""
Indicates whether the mailFolder is hidden. This property can be set only when creating the folder.
Find more information in Hidden mail folders.
"""
return self.properties.get("isHidden", None)
@property
def parent_folder_id(self):
# type: () -> Optional[str]
"""
The unique identifier for the mailFolder's parent mailFolder.
"""
return self.properties.get("parentFolderId", None)
@property
def total_item_count(self):
# type: () -> Optional[int]
"""The number of items in the mailFolder."""
return self.properties.get("totalItemCount", None)
@property
def unread_item_count(self):
# type: () -> Optional[int]
"""The number of items in the mailFolder marked as unread."""
return self.properties.get("unreadItemCount", None)
@property
def child_folders(self):
# type: () -> EntityCollection[MailFolder]
"""The collection of child folders in the mailFolder."""
return self.properties.get(
"childFolders",
EntityCollection(
self.context,
MailFolder,
ResourcePath("childFolders", self.resource_path),
),
)
@property
def message_rules(self):
# type: () -> EntityCollection[MessageRule]
""""""
return self.properties.get(
"messageRules",
EntityCollection(
self.context,
MessageRule,
ResourcePath("messageRules", self.resource_path),
),
)
@property
def messages(self):
# type: () -> MessageCollection
"""The collection of messages in the mailFolder."""
return self.properties.get(
"messages",
MessageCollection(
self.context, ResourcePath("messages", self.resource_path)
),
)
@property
def multi_value_extended_properties(self):
# type: () -> EntityCollection[MultiValueLegacyExtendedProperty]
"""The collection of multi-value extended properties defined for the MailFolder."""
return self.properties.get(
"multiValueExtendedProperties",
EntityCollection(
self.context,
MultiValueLegacyExtendedProperty,
ResourcePath("multiValueExtendedProperties", self.resource_path),
),
)
@property
def single_value_extended_properties(self):
# type: () -> EntityCollection[SingleValueLegacyExtendedProperty]
"""The collection of single-value extended properties defined for the MailFolder."""
return self.properties.get(
"singleValueExtendedProperties",
EntityCollection(
self.context,
SingleValueLegacyExtendedProperty,
ResourcePath("singleValueExtendedProperties", self.resource_path),
),
)
def get_property(self, name, default_value=None):
if default_value is None:
property_mapping = {
"childFolders": self.child_folders,
"messageRules": self.message_rules,
"multiValueExtendedProperties": self.multi_value_extended_properties,
"singleValueExtendedProperties": self.single_value_extended_properties,
}
default_value = property_mapping.get(name, None)
return super(MailFolder, self).get_property(name, default_value)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
Entity | - |
Parameter Details
context: The Office365 API context object required for making API calls. This is passed to the parent Entity class constructor and is used by all methods that interact with the Microsoft Graph API. It manages authentication, request queuing, and response handling.
Return Value
Instantiation returns a MailFolder object representing a specific mail folder in a user's mailbox. Methods return various types: copy() returns a new MailFolder instance; empty(), mark_all_items_as_read(), and mark_all_items_as_unread() return self for method chaining; properties return their respective types (int, str, bool, or collection objects like EntityCollection and MessageCollection).
Class Interface
Methods
copy(destination_id: str) -> MailFolder
Purpose: Copies the mail folder and its contents to another mail folder
Parameters:
destination_id: The folder ID or a well-known folder name (e.g., 'inbox', 'drafts') where the folder should be copied
Returns: A new MailFolder instance representing the copied folder
empty(delete_sub_folders: bool = False) -> MailFolder
Purpose: Empties the folder by deleting all messages, optionally including subfolders
Parameters:
delete_sub_folders: Boolean flag indicating whether subfolders should also be deleted (default: False)
Returns: Self (MailFolder instance) for method chaining
mark_all_items_as_read() -> MailFolder
Purpose: Marks all messages in the folder as read by iterating through all pages
Returns: Self (MailFolder instance) for method chaining
mark_all_items_as_unread() -> MailFolder
Purpose: Marks all messages in the folder as unread by iterating through all pages
Returns: Self (MailFolder instance) for method chaining
get_property(name: str, default_value=None) -> Any
Purpose: Retrieves a property value by name with special handling for collection properties
Parameters:
name: The property name to retrievedefault_value: Default value to return if property doesn't exist (optional)
Returns: The property value or default_value if not found
child_folder_count -> Optional[int]
property
Purpose: Gets the number of immediate child mail folders in the current folder
Returns: Integer count of child folders or None if not loaded
display_name -> Optional[str]
property
Purpose: Gets the display name of the mail folder
Returns: String name of the folder or None if not loaded
is_hidden -> Optional[bool]
property
Purpose: Indicates whether the mail folder is hidden (can only be set during folder creation)
Returns: Boolean indicating hidden status or None if not loaded
parent_folder_id -> Optional[str]
property
Purpose: Gets the unique identifier for the parent mail folder
Returns: String ID of the parent folder or None if not loaded
total_item_count -> Optional[int]
property
Purpose: Gets the total number of items in the mail folder
Returns: Integer count of all items or None if not loaded
unread_item_count -> Optional[int]
property
Purpose: Gets the number of unread items in the mail folder
Returns: Integer count of unread items or None if not loaded
child_folders -> EntityCollection[MailFolder]
property
Purpose: Gets the collection of child mail folders
Returns: EntityCollection containing MailFolder instances representing child folders
message_rules -> EntityCollection[MessageRule]
property
Purpose: Gets the collection of message rules defined for the folder
Returns: EntityCollection containing MessageRule instances
messages -> MessageCollection
property
Purpose: Gets the collection of messages in the mail folder
Returns: MessageCollection containing all messages in the folder
multi_value_extended_properties -> EntityCollection[MultiValueLegacyExtendedProperty]
property
Purpose: Gets the collection of multi-value extended properties defined for the folder
Returns: EntityCollection containing MultiValueLegacyExtendedProperty instances
single_value_extended_properties -> EntityCollection[SingleValueLegacyExtendedProperty]
property
Purpose: Gets the collection of single-value extended properties defined for the folder
Returns: EntityCollection containing SingleValueLegacyExtendedProperty instances
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
context |
ClientContext | The Office365 API context object inherited from Entity, used for executing queries and managing API communication | instance |
properties |
dict | Dictionary storing the folder's properties and data, inherited from Entity base class | instance |
resource_path |
ResourcePath | The API resource path for this folder entity, inherited from Entity base class | instance |
Dependencies
office365typing
Required Imports
from office365.outlook.mail.folders.folder import MailFolder
from office365.entity import Entity
from office365.entity_collection import EntityCollection
from office365.outlook.mail.messages.collection import MessageCollection
from office365.outlook.mail.messages.rules.rule import MessageRule
from office365.directory.extensions.extended_property import MultiValueLegacyExtendedProperty
from office365.directory.extensions.extended_property import SingleValueLegacyExtendedProperty
from office365.runtime.paths.resource_path import ResourcePath
from office365.runtime.queries.service_operation import ServiceOperationQuery
from typing import Optional
Usage Example
from office365.graph_client import GraphClient
from office365.outlook.mail.folders.folder import MailFolder
# Initialize client with credentials
client = GraphClient.with_username_and_password('user@domain.com', 'password')
# Get inbox folder
inbox = client.me.mail_folders.get_by_name('Inbox')
inbox.get().execute_query()
# Access folder properties
print(f"Folder: {inbox.display_name}")
print(f"Total items: {inbox.total_item_count}")
print(f"Unread items: {inbox.unread_item_count}")
# Copy folder to another location
copied_folder = inbox.copy('drafts')
copied_folder.execute_query()
# Mark all messages as read
inbox.mark_all_items_as_read()
# Access child folders
for child in inbox.child_folders:
print(child.display_name)
# Access messages in folder
for message in inbox.messages:
print(message.subject)
# Empty folder (delete all messages)
inbox.empty(delete_sub_folders=False)
Best Practices
- Always ensure the context object is properly authenticated before instantiating or using MailFolder instances
- Call execute_query() on the context after operations to commit changes to the server
- Use method chaining with empty(), mark_all_items_as_read(), and mark_all_items_as_unread() as they return self
- Be cautious with empty() method as it permanently deletes messages; consider the delete_sub_folders parameter carefully
- Access properties only after calling get().execute_query() to ensure data is loaded from the server
- Use well-known folder names (e.g., 'inbox', 'drafts', 'sentitems') when copying folders for better compatibility
- The mark_all_items_as_read/unread methods iterate through all pages of messages, which may take time for large folders
- Child folders, messages, and extended properties are lazy-loaded collections; access them only when needed
- The class maintains state through the properties dictionary inherited from Entity; modifications should use set_property() and update()
- For bulk operations on messages, the class uses page_loaded callbacks to process items in batches
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class MailFolderCollection 74.7% similar
-
class MailSearchFolder 71.9% similar
-
class Message 68.7% similar
-
class OutlookCategory 62.8% similar
-
class OutlookItem 62.3% similar