function main_v13
Orchestrates an email search and PDF attachment download workflow using Microsoft Graph API, including authentication, email search, result display, and attachment processing.
/tf/active/vicechatdev/mailsearch/email_search_app.py
436 - 505
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
msalrequestsosbase64csvtypingdatetimepathlib
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function main_v99 85.3% similar
-
function download_attachments_for_message 69.5% similar
-
class EmailSearchApp 69.4% similar
-
function main_v37 62.4% similar
-
function main_v102 62.1% similar