🔍 Code Extractor

class MessageCollection

Maturity: 36

A collection class for managing Microsoft Outlook email messages, extending DeltaCollection to provide message-specific operations like creating draft messages.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/outlook/mail/messages/collection.py
Lines:
8 - 29
Complexity:
moderate

Purpose

MessageCollection serves as a specialized collection container for Microsoft Outlook Message objects. It inherits from DeltaCollection to provide delta query capabilities and adds message-specific functionality for creating draft messages with subject, body, and recipients. This class is part of the Office365 SDK and is typically used to interact with a user's mailbox messages through the Microsoft Graph API.

Source Code

class MessageCollection(DeltaCollection[Message]):
    def __init__(self, context, resource_path=None):
        super(MessageCollection, self).__init__(context, Message, resource_path)

    def add(self, subject=None, body=None, to_recipients=None, **kwargs):
        """
        Create a draft of a new message in either JSON or MIME format.

        :param str subject: The subject of the message.
        :param str or ItemBody body: The body of the message. It can be in HTML or text format
        :param list[str] to_recipients:
        """
        if to_recipients is not None:
            kwargs["toRecipients"] = ClientValueCollection(
                Recipient, [Recipient.from_email(email) for email in to_recipients]
            )
        if body is not None:
            kwargs["body"] = body if isinstance(body, ItemBody) else ItemBody(body)
        if subject is not None:
            kwargs["subject"] = subject

        return super(MessageCollection, self).add(**kwargs)

Parameters

Name Type Default Kind
bases DeltaCollection[Message] -

Parameter Details

context: The client context object that provides authentication and connection information to the Microsoft Graph API. This is required for making API calls to retrieve or manipulate messages.

resource_path: Optional string representing the API endpoint path for this message collection. If not provided, it will be derived from the parent context. This allows the collection to know which mailbox or folder it represents.

Return Value

Instantiation returns a MessageCollection object that can be used to query, add, and manage email messages. The add() method returns a Message object representing the newly created draft message.

Class Interface

Methods

__init__(self, context, resource_path=None)

Purpose: Initializes a new MessageCollection instance with the provided context and optional resource path

Parameters:

  • context: The client context object for API communication
  • resource_path: Optional string path to the API resource endpoint

Returns: None (constructor)

add(self, subject=None, body=None, to_recipients=None, **kwargs) -> Message

Purpose: Creates a draft message with the specified subject, body, and recipients in either JSON or MIME format

Parameters:

  • subject: Optional string for the message subject line
  • body: Optional string or ItemBody object for the message body content (supports HTML or plain text)
  • to_recipients: Optional list of email address strings to be converted to Recipient objects
  • **kwargs: Additional message properties to set (e.g., ccRecipients, bccRecipients, importance)

Returns: A Message object representing the newly created draft message

Attributes

Name Type Description Scope
context ClientContext The client context inherited from parent class, used for API communication and authentication instance
resource_path str or None The API endpoint path for this message collection, inherited from parent class instance

Dependencies

  • office365

Required Imports

from office365.delta_collection import DeltaCollection
from office365.outlook.mail.item_body import ItemBody
from office365.outlook.mail.messages.message import Message
from office365.outlook.mail.recipient import Recipient
from office365.runtime.client_value_collection import ClientValueCollection

Usage Example

from office365.graph_client import GraphClient
from office365.outlook.mail.messages.message_collection import MessageCollection

# Authenticate and get client context
client = GraphClient.with_username_and_password(
    client_id='your_client_id',
    username='user@domain.com',
    password='password'
)

# Get the messages collection for the current user
messages = client.me.messages

# Create a new draft message
new_message = messages.add(
    subject='Meeting Tomorrow',
    body='Let\'s discuss the project updates.',
    to_recipients=['colleague@domain.com', 'manager@domain.com']
)
client.execute_query()

# Access the created message
print(f'Draft created with ID: {new_message.id}')

# Query messages with delta tracking
for message in messages:
    print(f'{message.subject} from {message.sender.email_address.address}')

Best Practices

  • Always call execute_query() on the client context after adding messages to persist changes to the server
  • Use the add() method's convenience parameters (subject, body, to_recipients) for simple message creation rather than constructing Message objects manually
  • The body parameter can accept either a string or an ItemBody object; strings are automatically converted to ItemBody
  • Email addresses in to_recipients are automatically converted to Recipient objects
  • This collection supports delta queries inherited from DeltaCollection, allowing efficient synchronization of message changes
  • The collection is typically accessed through a parent context (e.g., client.me.messages) rather than instantiated directly
  • Additional message properties can be set using **kwargs in the add() method for properties not covered by the convenience parameters

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class MailFolderCollection 77.9% similar

    A collection class for managing Microsoft Outlook mail folders with delta query support, inheriting from DeltaCollection to provide change tracking capabilities.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/outlook/mail/folders/collection.py
  • class ContactCollection 75.8% similar

    A collection class for managing Microsoft Outlook contacts, providing methods to add and manage Contact objects within a contact folder or root Contacts folder.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/outlook/contacts/collection.py
  • class Message 73.9% similar

    Represents an email message in a Microsoft Outlook mailbox folder, providing methods for message operations like sending, replying, forwarding, and managing attachments.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/outlook/mail/messages/message.py
  • class EventCollection 70.7% similar

    A collection class for managing Microsoft Outlook calendar events, providing methods to create and manage events with attendees, time zones, and other properties.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/outlook/calendar/events/collection.py
  • class GroupCollection 64.4% similar

    A collection class for managing Microsoft Graph API Group resources, providing methods to create, retrieve, and manage groups including Microsoft 365 groups and Security groups.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/groups/collection.py
← Back to Browse