🔍 Code Extractor

class ContactCollection

Maturity: 40

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

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

Purpose

ContactCollection is a specialized collection class that extends DeltaCollection to manage Contact objects in Microsoft Outlook/Office 365. It provides a convenient interface for adding contacts with common properties like name, email, and phone number. The class handles the conversion of simple parameters into the appropriate Office 365 data structures (EmailAddress, StringCollection) required by the API. It supports delta queries for efficient synchronization of contact data.

Source Code

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

    def add(
        self, given_name, surname, email_address=None, business_phone=None, **kwargs
    ):
        """
        Add a contact to the root Contacts folder or to the contacts endpoint of another contact folder.
        :param str given_name: The contact's given name.
        :param str surname: The contact's surname.
        :param str email_address: Default email address
        :param str business_phone: Default contact's business phone number.
        """

        def _create_email_address(address):
            return EmailAddress(address, "{0} {1}".format(given_name, surname))

        kwargs["givenName"] = given_name
        kwargs["surname"] = surname
        if email_address:
            kwargs["emailAddresses"] = ClientValueCollection(
                EmailAddress, [_create_email_address(email_address)]
            )
        if business_phone:
            kwargs["businessPhones"] = StringCollection([business_phone])
        return super(ContactCollection, self).add(**kwargs)

Parameters

Name Type Default Kind
bases DeltaCollection[Contact] -

Parameter Details

context: The client context object that provides authentication and connection information to the Office 365 service. This is typically an instance of ClientContext or similar authentication context required for API calls.

resource_path: Optional string representing the URL path to the specific contact collection resource in the Office 365 API. If None, defaults to the root Contacts folder. Used to target specific contact folders or endpoints.

Return Value

The __init__ method returns a ContactCollection instance. The add() method returns a Contact object representing the newly created contact in the collection. The Contact object will have all the properties set according to the parameters provided, including givenName, surname, emailAddresses, and businessPhones.

Class Interface

Methods

__init__(self, context, resource_path=None)

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

Parameters:

  • context: The client context object for Office 365 API authentication and communication
  • resource_path: Optional string path to the specific contact collection resource; defaults to None for root Contacts folder

Returns: None (constructor)

add(self, given_name, surname, email_address=None, business_phone=None, **kwargs)

Purpose: Creates and adds a new contact to the collection with the specified properties

Parameters:

  • given_name: The contact's first/given name (required)
  • surname: The contact's last/family name (required)
  • email_address: Optional default email address for the contact; will be converted to EmailAddress object
  • business_phone: Optional business phone number; will be converted to StringCollection
  • **kwargs: Additional contact properties (e.g., jobTitle, companyName, mobilePhone) passed to the parent add method

Returns: A Contact object representing the newly created contact with all specified properties

Attributes

Name Type Description Scope
context ClientContext Inherited from parent class; stores the authentication context for API calls instance
resource_path str or None Inherited from parent class; stores the URL path to the contact collection resource instance

Dependencies

  • office365
  • office365.delta_collection
  • office365.outlook.calendar.email_address
  • office365.outlook.contacts.contact
  • office365.runtime.client_value_collection
  • office365.runtime.types.collections

Required Imports

from office365.delta_collection import DeltaCollection
from office365.outlook.calendar.email_address import EmailAddress
from office365.outlook.contacts.contact import Contact
from office365.runtime.client_value_collection import ClientValueCollection
from office365.runtime.types.collections import StringCollection

Usage Example

from office365.graph_client import GraphClient
from office365.outlook.contacts.collection import ContactCollection

# Authenticate and get context
client = GraphClient.with_username_and_password(tenant_name, client_id, username, password)
context = client.context

# Get the contacts collection
contacts = ContactCollection(context, 'me/contacts')

# Add a new contact with basic information
new_contact = contacts.add(
    given_name='John',
    surname='Doe',
    email_address='john.doe@example.com',
    business_phone='+1-555-0100'
)

# Add a contact with additional properties
advanced_contact = contacts.add(
    given_name='Jane',
    surname='Smith',
    email_address='jane.smith@example.com',
    business_phone='+1-555-0200',
    jobTitle='Software Engineer',
    companyName='Tech Corp'
)

# Execute the request
context.execute_query()

Best Practices

  • Always provide a valid context object with proper authentication before instantiating ContactCollection
  • Call context.execute_query() after adding contacts to persist changes to the server
  • Use the add() method rather than manually constructing Contact objects to ensure proper data structure formatting
  • The email_address and business_phone parameters are optional but recommended for creating useful contacts
  • Additional contact properties can be passed via **kwargs to the add() method for extended contact information
  • The class automatically handles conversion of simple strings to complex Office 365 types (EmailAddress, StringCollection)
  • Resource_path should point to a valid contacts endpoint (e.g., 'me/contacts' or 'users/{id}/contacts')
  • This class inherits from DeltaCollection, so it supports delta queries for efficient synchronization
  • Handle API exceptions appropriately as network calls may fail due to authentication or permission issues

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class MailFolderCollection 75.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 MessageCollection 75.8% similar

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

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/outlook/mail/messages/collection.py
  • class EventCollection 72.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 UserCollection 69.4% similar

    UserCollection is a specialized collection class for managing User objects in Microsoft 365/Office 365 directory services, providing methods to retrieve, create, and manage users with delta query support.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/users/collection.py
  • class ApplicationCollection 67.1% similar

    A collection class for managing Application objects in a directory, providing methods to retrieve and manage applications with delta query support.

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