function search_messages
Searches Microsoft Graph API for email messages from a specific sender containing a keyword, with automatic pagination handling.
/tf/active/vicechatdev/mailsearch/example_script.py
55 - 102
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
requestsmsal
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class EmailSearchApp 61.6% similar
-
function main_v99 60.8% similar
-
function test_email_search 60.6% similar
-
function download_attachments_for_message 59.8% similar
-
function main_v13 58.1% similar