🔍 Code Extractor

function search_messages

Maturity: 56

Searches Microsoft Graph API for email messages from a specific sender containing a keyword, with automatic pagination handling.

File:
/tf/active/vicechatdev/mailsearch/example_script.py
Lines:
55 - 102
Complexity:
moderate

Purpose

This function queries the Microsoft Graph API's /me/messages endpoint to retrieve email messages that match both a sender email address and contain a specific keyword in the subject or body. It handles pagination automatically to retrieve all matching messages across multiple API calls, making it useful for email search and filtering operations in Microsoft 365/Outlook integrations.

Source Code

def search_messages(access_token: str, sender: str, keyword: str):
    """
    Uses the Graph /me/messages endpoint with OData query parameters.
    We use $search to find keyword, and $filter for from/emailAddress/address.
    """
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Accept": "application/json"
    }

    # Base URL
    if USE_ME_ENDPOINT:
        base_url = "https://graph.microsoft.com/v1.0/me/messages"
    else:
        # Example if you want another user:
        # base_url = "https://graph.microsoft.com/v1.0/users/USER_ID/messages"
        raise NotImplementedError("Update base_url for specific user if not using /me.")

    # NOTE: Graph search syntax for $search: "invoice" will search subject/body
    # We combine $search with $filter on sender address.
    params = {
        "$search": f'"{keyword}"',
        "$filter": f"from/emailAddress/address eq '{sender}'",
        "$top": "25"
    }

    messages = []

    url = base_url
    while True:
        response = requests.get(url, headers=headers, params=params)
        if response.status_code != 200:
            raise RuntimeError(f"Error searching messages: {response.status_code} {response.text}")

        data = response.json()
        batch = data.get("value", [])
        messages.extend(batch)

        # Handle pagination
        next_link = data.get("@odata.nextLink")
        if not next_link:
            break

        # After the first call, nextLink already contains params
        url = next_link
        params = None  # Ensure we don't pass params again

    return messages

Parameters

Name Type Default Kind
access_token str - positional_or_keyword
sender str - positional_or_keyword
keyword str - positional_or_keyword

Parameter Details

access_token: A valid OAuth 2.0 bearer token for authenticating with Microsoft Graph API. Must have appropriate permissions (Mail.Read or Mail.ReadWrite) to access the user's messages.

sender: The email address of the sender to filter by. Must be a complete email address (e.g., 'user@example.com'). Used in the OData $filter query parameter to match the from/emailAddress/address field.

keyword: The search term to find in message subjects and bodies. Will be wrapped in quotes for exact phrase matching in the $search query parameter. Can be a single word or phrase.

Return Value

Returns a list of message objects (dictionaries) matching the search criteria. Each message object contains standard Microsoft Graph message properties including id, subject, body, from, receivedDateTime, etc. Returns an empty list if no messages match the criteria. The list aggregates results from all paginated API responses.

Dependencies

  • requests
  • msal

Required Imports

import requests

Usage Example

import requests
import msal

# Acquire access token using MSAL
client_id = 'your-client-id'
client_secret = 'your-client-secret'
tenant_id = 'your-tenant-id'

app = msal.ConfidentialClientApplication(
    client_id,
    authority=f'https://login.microsoftonline.com/{tenant_id}',
    client_credential=client_secret
)

result = app.acquire_token_for_client(scopes=['https://graph.microsoft.com/.default'])
access_token = result['access_token']

# Set the required global variable
USE_ME_ENDPOINT = True

# Search for messages
messages = search_messages(
    access_token=access_token,
    sender='colleague@example.com',
    keyword='invoice'
)

print(f'Found {len(messages)} messages')
for msg in messages:
    print(f"Subject: {msg['subject']}, Received: {msg['receivedDateTime']}")

Best Practices

  • Ensure the access token has not expired before calling this function; implement token refresh logic if needed
  • The USE_ME_ENDPOINT global variable must be defined and set to True before calling this function
  • Be aware that $search queries may have performance implications with large mailboxes; consider using $top parameter judiciously
  • Handle the RuntimeError exception that may be raised if the API call fails
  • The function retrieves all matching messages through pagination, which could result in large result sets and memory usage
  • The sender parameter must be an exact email address match; partial matches are not supported
  • Keyword searches are performed on both subject and body fields by default in Microsoft Graph
  • Consider implementing rate limiting or retry logic for production use to handle API throttling
  • The function uses synchronous requests; for high-volume operations, consider implementing async alternatives

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class EmailSearchApp 61.6% similar

    A class for authenticating with Microsoft Graph API and searching emails in a user's mailbox, with support for downloading PDF attachments and maintaining download records.

    From: /tf/active/vicechatdev/mailsearch/email_search_app.py
  • function main_v99 60.8% similar

    Main entry point function that authenticates with Microsoft Graph API, searches for emails from a specific sender containing a keyword, and downloads all attachments from matching messages to a local directory.

    From: /tf/active/vicechatdev/mailsearch/example_script.py
  • function test_email_search 60.6% similar

    Tests the email search functionality of a VendorEmailExtractor instance by searching for emails containing common business terms in the first available mailbox.

    From: /tf/active/vicechatdev/find_email/test_vendor_extractor.py
  • function download_attachments_for_message 59.8% similar

    Downloads file attachments from a Microsoft Graph API email message to a specified local directory, handling duplicate filenames automatically.

    From: /tf/active/vicechatdev/mailsearch/example_script.py
  • function main_v13 58.1% similar

    Orchestrates an email search and PDF attachment download workflow using Microsoft Graph API, including authentication, email search, result display, and attachment processing.

    From: /tf/active/vicechatdev/mailsearch/email_search_app.py
← Back to Browse