šŸ” Code Extractor

function main_v13

Maturity: 50

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

File:
/tf/active/vicechatdev/mailsearch/email_search_app.py
Lines:
436 - 505
Complexity:
complex

Purpose

This is the main entry point for an email search application that connects to Microsoft 365, searches for emails based on sender and keyword criteria, displays results, downloads PDF attachments, and generates a download register. It handles the complete workflow from authentication through file download and metadata tracking.

Source Code

def main():
    """Main execution function"""
    
    # Initialize the application
    app = EmailSearchApp(
        tenant_id=TENANT_ID,
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        target_mailbox=TARGET_MAILBOX
    )
    
    try:
        # Step 1: Authenticate user
        app.authenticate(SCOPES)
        
        # Step 2: Search for emails
        emails = app.search_emails(
            sender=SENDER_EMAIL,
            keyword=SEARCH_KEYWORD,
            max_results=50  # Results per page
        )
        
        # Step 3: Display results
        app.display_email_list(emails)
        
        # Step 4: Download PDF attachments
        if emails:
            print(f"\n{'='*80}")
            print("Downloading PDF Attachments")
            print(f"{'='*80}\n")
            
            all_download_records = []
            
            for idx, email in enumerate(emails, 1):
                subject = email.get("subject", "(No Subject)")
                has_attachments = email.get("hasAttachments", False)
                
                print(f"[{idx}] Processing: {subject[:60]}...")
                
                if not has_attachments:
                    print(f"  ⊘ No attachments")
                    continue
                
                # Download returns metadata for each file
                download_metadata = app.download_pdf_attachments(
                    email=email,
                    output_dir=OUTPUT_DIR
                )
                
                all_download_records.extend(download_metadata)
            
            # Save register
            if all_download_records:
                app.save_download_register(all_download_records, REGISTER_FILE)
            
            print(f"\n{'='*80}")
            print(f"āœ“ Download completed!")
            print(f"Total PDF files downloaded: {len(all_download_records)}")
            print(f"Saved to: {os.path.abspath(OUTPUT_DIR)}")
            print(f"Register: {os.path.abspath(REGISTER_FILE)}")
            print(f"{'='*80}")
        
        print(f"\nāœ“ Search completed successfully!")
        print(f"Total emails found: {len(emails)}")
        
    except KeyboardInterrupt:
        print("\n\nāœ— Operation cancelled by user")
    except Exception as e:
        print(f"\nāœ— Error occurred: {str(e)}")
        raise

Return Value

This function does not return any value (implicitly returns None). It performs side effects including console output, file downloads to OUTPUT_DIR, and creation of a CSV register file at REGISTER_FILE location.

Dependencies

  • msal
  • requests
  • os
  • base64
  • csv
  • typing
  • datetime
  • pathlib

Required Imports

import os
import base64
import csv
import msal
import requests
from typing import List, Dict, Optional
from datetime import datetime
from pathlib import Path

Usage Example

# Configuration constants
TENANT_ID = 'your-tenant-id'
CLIENT_ID = 'your-client-id'
CLIENT_SECRET = 'your-client-secret'
TARGET_MAILBOX = 'user@example.com'
SCOPES = ['https://graph.microsoft.com/.default']
SENDER_EMAIL = 'sender@example.com'
SEARCH_KEYWORD = 'invoice'
OUTPUT_DIR = './downloads'
REGISTER_FILE = './download_register.csv'

# Ensure EmailSearchApp class is defined
# from email_search_app import EmailSearchApp

if __name__ == '__main__':
    main()

Best Practices

  • Ensure all required configuration constants (TENANT_ID, CLIENT_ID, etc.) are defined before calling this function
  • The EmailSearchApp class must be properly implemented with all required methods
  • Verify that the Azure AD application has appropriate Microsoft Graph API permissions (Mail.Read, Mail.ReadWrite)
  • Ensure OUTPUT_DIR exists or the application has permissions to create it
  • Handle KeyboardInterrupt gracefully to allow users to cancel long-running operations
  • The function uses max_results=50 for pagination; adjust based on expected email volume
  • Monitor console output for progress updates and error messages
  • Review the generated CSV register file for audit trail of downloaded attachments
  • Implement proper secret management for CLIENT_SECRET (use environment variables or key vault)
  • Consider implementing retry logic for network failures in the EmailSearchApp class methods

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function main_v99 85.3% 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 download_attachments_for_message 69.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 69.4% 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_v37 62.4% similar

    Demonstrates example usage of the VendorEmailExtractor class by searching for vendor emails across Office 365 mailboxes and displaying results.

    From: /tf/active/vicechatdev/find_email/vendor_email_extractor.py
  • function main_v102 62.1% similar

    Main entry point function that orchestrates a document comparison workflow between two folders (mailsearch/output and wuxi2 repository), detecting signatures and generating comparison results.

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