🔍 Code Extractor

class InformationProtection

Maturity: 50

A class that provides methods to interact with Microsoft Purview Information Protection services, specifically for creating threat assessment requests for email messages.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/protection/information.py
Lines:
11 - 62
Complexity:
moderate

Purpose

This class serves as an interface to Microsoft Purview Information Protection APIs, allowing users to create mail assessment requests to evaluate potential security threats in email messages. It extends the Entity base class and manages threat assessment requests through the Microsoft Graph API. The primary use case is to submit emails for security analysis to determine if they contain spam, phishing, malware, or other threats.

Source Code

class InformationProtection(Entity):
    """Exposes methods that you can use to get Microsoft Purview Information Protection labels and label policies."""

    def create_mail_assessment(
        self, message, recipient=None, expected_assessment="block", category="spam"
    ):
        """
        Create a mail assessment request
        :param str recipient: Recipient email
        :param office365.outlook.mail.messages.message.Message message: Message object or identifier
        :param str expected_assessment:
        :param str category:
        """

        from office365.directory.protection.threatassessment.mail_request import (
            MailAssessmentRequest,
        )

        return_type = MailAssessmentRequest(self.context)
        self.threat_assessment_requests.add_child(return_type)

        def _construct_request(request):
            # type: (RequestOptions) -> None
            request.set_header("Content-Type", "application/json")

        def _create_and_add_query():
            return_type.set_property(
                "recipientEmail", str(message.to_recipients[0].emailAddress)
            )
            return_type.set_property("expectedAssessment", expected_assessment)
            return_type.set_property("category", category)
            return_type.set_property("message", message.resource_url)
            qry = CreateEntityQuery(
                self.threat_assessment_requests, return_type, return_type
            )
            self.context.add_query(qry).before_query_execute(_construct_request)

        message.ensure_properties(["id", "toRecipients"], _create_and_add_query)
        return return_type

    @property
    def threat_assessment_requests(self):
        # type: () -> EntityCollection[ThreatAssessmentRequest]
        """"""
        return self.properties.get(
            "threatAssessmentRequests",
            EntityCollection(
                self.context,
                ThreatAssessmentRequest,
                ResourcePath("threatAssessmentRequests", self.resource_path),
            ),
        )

Parameters

Name Type Default Kind
bases Entity -

Parameter Details

context: The execution context inherited from Entity base class, which manages API communication, authentication, and request handling for Microsoft Graph API operations. This is typically passed during instantiation and is required for all API interactions.

Return Value

Instantiation returns an InformationProtection object that provides access to threat assessment functionality. The create_mail_assessment method returns a MailAssessmentRequest object representing the created assessment request, which can be used to track the status and results of the security evaluation.

Class Interface

Methods

create_mail_assessment(message, recipient=None, expected_assessment='block', category='spam') -> MailAssessmentRequest

Purpose: Creates a threat assessment request for an email message to evaluate potential security threats such as spam, phishing, or malware

Parameters:

  • message: A Message object or message identifier representing the email to be assessed. Must have 'id' and 'toRecipients' properties available
  • recipient: Optional recipient email address as a string. If not provided, uses the first recipient from message.to_recipients
  • expected_assessment: Expected assessment result, either 'block' or 'unblock'. Defaults to 'block'. Indicates what action is expected based on the assessment
  • category: Category of threat to assess. Valid values include 'spam', 'phishing', 'malware'. Defaults to 'spam'

Returns: A MailAssessmentRequest object representing the created assessment request, which can be used to track the assessment status and retrieve results

threat_assessment_requests -> EntityCollection[ThreatAssessmentRequest] property

Purpose: Provides access to the collection of all threat assessment requests associated with this Information Protection instance

Returns: An EntityCollection containing ThreatAssessmentRequest objects, allowing querying, filtering, and accessing existing threat assessment requests

Attributes

Name Type Description Scope
context ClientContext The execution context inherited from Entity base class that manages API communication, authentication, and request handling instance
properties dict Dictionary storing entity properties including the threatAssessmentRequests collection, inherited from Entity base class instance
resource_path ResourcePath The resource path for this entity in the Microsoft Graph API hierarchy, inherited from Entity base class instance

Dependencies

  • office365
  • office365.directory.protection.threatassessment.request
  • office365.directory.protection.threatassessment.mail_request
  • office365.entity
  • office365.entity_collection
  • office365.runtime.http.request_options
  • office365.runtime.paths.resource_path
  • office365.runtime.queries.create_entity
  • office365.outlook.mail.messages.message

Required Imports

from office365.directory.protection.information_protection import InformationProtection
from office365.directory.protection.threatassessment.request import ThreatAssessmentRequest
from office365.entity import Entity
from office365.entity_collection import EntityCollection
from office365.runtime.http.request_options import RequestOptions
from office365.runtime.paths.resource_path import ResourcePath
from office365.runtime.queries.create_entity import CreateEntityQuery

Conditional/Optional Imports

These imports are only needed under specific conditions:

from office365.directory.protection.threatassessment.mail_request import MailAssessmentRequest

Condition: only when calling create_mail_assessment method

Required (conditional)

Usage Example

from office365.graph_client import GraphClient
from office365.outlook.mail.messages.message import Message

# Initialize Graph client with credentials
client = GraphClient(lambda: ('your_token',))

# Get Information Protection service
info_protection = client.information_protection

# Get a message to assess
message = client.me.messages.get_by_id('message_id')

# Create a mail assessment request
assessment = info_protection.create_mail_assessment(
    message=message,
    recipient='user@example.com',
    expected_assessment='block',
    category='spam'
)

# Execute the request
client.execute_query()

# Access the assessment results
print(f'Assessment ID: {assessment.id}')
print(f'Status: {assessment.status}')

Best Practices

  • Always ensure the message object has required properties ('id', 'toRecipients') loaded before calling create_mail_assessment, or the method will automatically load them
  • The context object must be properly authenticated with sufficient permissions to access Microsoft Purview Information Protection APIs
  • Call execute_query() on the context after creating assessment requests to actually submit them to the API
  • Handle the asynchronous nature of threat assessments - results may not be immediately available
  • Use appropriate expected_assessment values: 'block' or 'unblock' to indicate what action you expect
  • Valid category values include 'spam', 'phishing', 'malware' - choose the appropriate category for your assessment
  • The threat_assessment_requests property provides access to all assessment requests and should be used to query existing assessments
  • Ensure proper error handling as API calls may fail due to network issues, authentication problems, or invalid message references

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class MailAssessmentRequest 67.2% similar

    A class representing a mail threat assessment request that inherits from ThreatAssessmentRequest, used to create and retrieve mail-based security threat assessments in Microsoft 365.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/protection/threatassessment/mail_request.py
  • class ThreatAssessmentRequest 64.9% similar

    An abstract base class representing a threat assessment request item, inheriting from Entity. This class serves as a foundation for concrete threat assessment request implementations.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/protection/threatassessment/request.py
  • class ThreatIntelligence 64.2% similar

    A class that provides APIs to retrieve threat intelligence information from Microsoft Graph, including data about hosts, threat articles, indicators of compromise, and enrichment data.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/security/threatintelligence/threat_intelligence.py
  • class EdiscoveryCase 63.0% similar

    Represents an eDiscovery case in Microsoft Purview eDiscovery (Premium), containing custodians, searches, and review sets for legal discovery processes.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/security/cases/ediscovery.py
  • class IntelligenceProfile 61.2% similar

    A class representing Microsoft Defender Threat Intelligence Profiles, providing access to threat actor infrastructure data and intelligence profiles for security operations teams.

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