🔍 Code Extractor

function download_attachments_for_message

Maturity: 53

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

File:
/tf/active/vicechatdev/mailsearch/example_script.py
Lines:
105 - 141
Complexity:
moderate

Purpose

This function retrieves all attachments associated with a specific email message via Microsoft Graph API, filters for file attachments (excluding item attachments), decodes the base64-encoded content, and saves them to disk. It handles filename conflicts by appending counters to duplicate names and provides console feedback on download status.

Source Code

def download_attachments_for_message(access_token: str, message_id: str, download_dir: str):
    """
    Get attachments for a message and download any file attachments.
    """
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Accept": "application/json"
    }

    url = f"https://graph.microsoft.com/v1.0/me/messages/{message_id}/attachments"
    response = requests.get(url, headers=headers)

    if response.status_code != 200:
        print(f"Failed to get attachments for message {message_id}: {response.status_code} {response.text}")
        return

    attachments = response.json().get("value", [])
    for att in attachments:
        # There are ItemAttachment and FileAttachment types. We want file ones.
        if att.get("@odata.type") == "#microsoft.graph.fileAttachment":
            name = att.get("name", "attachment")
            content_bytes = att.get("contentBytes")
            if not content_bytes:
                continue

            file_path = os.path.join(download_dir, name)

            # If duplicate names, add a counter
            base, ext = os.path.splitext(file_path)
            counter = 1
            while os.path.exists(file_path):
                file_path = f"{base}_{counter}{ext}"
                counter += 1

            with open(file_path, "wb") as f:
                f.write(base64.b64decode(content_bytes))
            print(f"Downloaded attachment: {file_path}")

Parameters

Name Type Default Kind
access_token str - positional_or_keyword
message_id str - positional_or_keyword
download_dir str - positional_or_keyword

Parameter Details

access_token: OAuth 2.0 bearer token for authenticating with Microsoft Graph API. Must have appropriate permissions (Mail.Read or Mail.ReadWrite) to access message attachments.

message_id: Unique identifier of the email message in Microsoft Graph. This is the message ID returned from Graph API queries (e.g., from /me/messages endpoint).

download_dir: Local filesystem path (string) where attachments should be saved. Directory must exist before calling this function, otherwise file write operations will fail.

Return Value

This function returns None (implicit). It performs side effects by writing files to disk and printing status messages to console. Success is indicated by console output showing downloaded file paths; failures print error messages with HTTP status codes.

Dependencies

  • requests
  • msal
  • os (standard library)
  • base64 (standard library)
  • pathlib (standard library)

Required Imports

import os
import base64
import requests

Usage Example

import os
import base64
import requests

# Ensure download directory exists
download_dir = './email_attachments'
os.makedirs(download_dir, exist_ok=True)

# Obtain access token (example using MSAL)
import msal
app = msal.PublicClientApplication(
    client_id='your-client-id',
    authority='https://login.microsoftonline.com/common'
)
result = app.acquire_token_interactive(scopes=['Mail.Read'])
access_token = result['access_token']

# Download attachments for a specific message
message_id = 'AAMkAGI2THVSAAA='
download_attachments_for_message(access_token, message_id, download_dir)

# Output: Downloaded attachment: ./email_attachments/document.pdf
#         Downloaded attachment: ./email_attachments/image.png

Best Practices

  • Always ensure the download_dir exists before calling this function using os.makedirs(download_dir, exist_ok=True)
  • Validate the access_token has appropriate Microsoft Graph permissions (Mail.Read minimum) before calling
  • Consider implementing error handling around this function as it prints errors but doesn't raise exceptions
  • Be aware that large attachments may consume significant memory as the entire file content is loaded into memory during base64 decoding
  • The function only downloads fileAttachment types; itemAttachment types (embedded messages, contacts) are skipped
  • Filename collision handling is basic (appending counters); consider implementing more sophisticated naming strategies for production use
  • Consider adding rate limiting or retry logic when processing multiple messages to avoid API throttling
  • The access_token should be refreshed if expired; implement token refresh logic in production scenarios

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function main_v99 74.5% 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 main_v13 69.5% 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 send_email_ms365 61.9% similar

    Sends an email through Microsoft 365 Graph API with support for HTML content, multiple recipients (to/cc/bcc), and file attachments.

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • class EmailSearchApp 61.1% 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 send_email_ms365_v1 61.0% similar

    Sends an email through the Microsoft 365 Graph API with support for HTML content, multiple recipients, CC/BCC, and file attachments.

    From: /tf/active/vicechatdev/CDocs single class/utils/notifications.py
← Back to Browse