🔍 Code Extractor

function main_v99

Maturity: 38

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.

File:
/tf/active/vicechatdev/mailsearch/example_script.py
Lines:
144 - 158
Complexity:
moderate

Purpose

This function orchestrates an automated email attachment download workflow. It authenticates using MSAL (Microsoft Authentication Library), queries Microsoft Graph API for emails matching specific criteria (sender and keyword), and downloads all attachments from the found messages. This is useful for automated document retrieval, backup systems, or processing incoming attachments from specific sources.

Source Code

def main():
    ensure_download_dir(DOWNLOAD_DIR)

    app = get_msal_app(CLIENT_ID, TENANT_ID)
    token = get_access_token(app, GRAPH_SCOPE)

    print(f"Searching for messages from {SENDER_EMAIL} containing '{KEYWORD}'...")
    messages = search_messages(token, SENDER_EMAIL, KEYWORD)
    print(f"Found {len(messages)} messages.")

    for msg in messages:
        subject = msg.get("subject", "(no subject)")
        msg_id = msg.get("id")
        print(f"\nMessage: {subject}")
        download_attachments_for_message(token, msg_id, DOWNLOAD_DIR)

Return Value

This function does not return any value (implicitly returns None). It performs side effects including: printing search results and progress to console, creating directories, and downloading files to the filesystem.

Dependencies

  • os
  • base64
  • requests
  • msal
  • pathlib

Required Imports

import os
import base64
import requests
import msal
from pathlib import Path

Usage Example

# Define required constants and helper functions first
DOWNLOAD_DIR = './downloads'
CLIENT_ID = 'your-client-id-here'
TENANT_ID = 'your-tenant-id-here'
GRAPH_SCOPE = ['https://graph.microsoft.com/.default']
SENDER_EMAIL = 'sender@example.com'
KEYWORD = 'invoice'

# Helper functions (simplified examples)
def ensure_download_dir(path):
    Path(path).mkdir(parents=True, exist_ok=True)

def get_msal_app(client_id, tenant_id):
    authority = f'https://login.microsoftonline.com/{tenant_id}'
    return msal.ConfidentialClientApplication(client_id, authority=authority, client_credential='secret')

def get_access_token(app, scopes):
    result = app.acquire_token_for_client(scopes=scopes)
    return result['access_token']

def search_messages(token, sender, keyword):
    # Implementation to search messages
    return []

def download_attachments_for_message(token, msg_id, download_dir):
    # Implementation to download attachments
    pass

# Run the main function
if __name__ == '__main__':
    main()

Best Practices

  • Ensure all required constants (CLIENT_ID, TENANT_ID, SENDER_EMAIL, KEYWORD, DOWNLOAD_DIR, GRAPH_SCOPE) are defined before calling this function
  • All helper functions (ensure_download_dir, get_msal_app, get_access_token, search_messages, download_attachments_for_message) must be implemented and available in scope
  • The Azure AD application must have appropriate permissions granted and admin consent provided for Mail.Read or Mail.ReadWrite
  • Store sensitive credentials (CLIENT_ID, TENANT_ID, client secrets) in environment variables or secure configuration, not hardcoded
  • Consider adding error handling around API calls and file operations for production use
  • The function prints to console - consider using logging module for better control in production environments
  • Ensure sufficient disk space is available in DOWNLOAD_DIR before running
  • Be aware of API rate limits when processing large numbers of messages
  • This function is designed to be called as a script entry point, typically wrapped in 'if __name__ == "__main__"' block

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function main_v13 85.3% 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
  • function download_attachments_for_message 74.5% 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
  • class EmailSearchApp 72.2% 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 get_ms365_token_v1 65.6% similar

    Authenticates with Microsoft 365 using MSAL (Microsoft Authentication Library) and retrieves an OAuth access token for the Microsoft Graph API.

    From: /tf/active/vicechatdev/CDocs single class/utils/notifications.py
  • function test_mailbox_access 63.3% similar

    Tests the ability to access and retrieve mailboxes from Microsoft Graph API through a VendorEmailExtractor instance, displaying results and troubleshooting information.

    From: /tf/active/vicechatdev/find_email/test_vendor_extractor.py
← Back to Browse