Working with Attachments

PyMailAI provides comprehensive support for handling email attachments in both incoming and outgoing messages.

Receiving Attachments

When processing incoming emails, attachments are automatically handled and made available through the EmailData.attachments list. Each attachment is represented as a dictionary containing the following fields:

  • filename: The name of the attached file

  • content_type: The MIME type of the attachment

  • payload: The binary content of the attachment

Here’s an example of processing received attachments:

async def message_handler(message: EmailData):
    # Process each attachment in the email
    for attachment in message.attachments:
        filename = attachment['filename']
        content = attachment['payload']
        content_type = attachment['content_type']

        # Example: Save attachment to file
        with open(filename, 'wb') as f:
            f.write(content)

        # Or process based on content type
        if content_type == 'application/pdf':
            # Handle PDF attachment
            process_pdf(content)
        elif content_type.startswith('image/'):
            # Handle image attachment
            process_image(content)

Sending Attachments

To send an email with attachments, include them in the attachments list when creating an EmailData object. Each attachment should be a dictionary with the same structure as received attachments.

Here’s an example of sending an email with attachments:

from datetime import datetime
from pymailai.message import EmailData

# Example: Sending a PDF file
with open('document.pdf', 'rb') as f:
    pdf_content = f.read()

# Create email with attachment
email = EmailData(
    message_id="",  # Will be generated by email server
    subject="Document Attached",
    from_address="sender@example.com",
    to_addresses=["recipient@example.com"],
    cc_addresses=[],
    body_text="Please find the attached document.",
    body_html=None,
    timestamp=datetime.now(),
    attachments=[{
        'filename': 'document.pdf',
        'content_type': 'application/pdf',
        'payload': pdf_content
    }]
)

# Send the email using your EmailAgent
await agent.send_message(email)

Multiple Attachments

You can include multiple attachments in a single email:

# Example: Email with multiple attachments
email = EmailData(
    message_id="",
    subject="Multiple Attachments",
    from_address="sender@example.com",
    to_addresses=["recipient@example.com"],
    cc_addresses=[],
    body_text="Please find the attached files.",
    body_html=None,
    timestamp=datetime.now(),
    attachments=[
        {
            'filename': 'document.pdf',
            'content_type': 'application/pdf',
            'payload': pdf_content
        },
        {
            'filename': 'image.jpg',
            'content_type': 'image/jpeg',
            'payload': image_content
        },
        {
            'filename': 'data.csv',
            'content_type': 'text/csv',
            'payload': csv_content
        }
    ]
)

Common MIME Types

Here are some common MIME types for attachments:

  • PDF files: application/pdf

  • Images:
    • JPEG: image/jpeg

    • PNG: image/png

    • GIF: image/gif

  • Documents:
    • Word: application/msword or application/vnd.openxmlformats-officedocument.wordprocessingml.document

    • Excel: application/vnd.ms-excel or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

    • PowerPoint: application/vnd.ms-powerpoint or application/vnd.openxmlformats-officedocument.presentationml.presentation

  • Text files:
    • Plain text: text/plain

    • CSV: text/csv

    • HTML: text/html

  • Archives:
    • ZIP: application/zip

    • RAR: application/x-rar-compressed

    • 7z: application/x-7z-compressed

The library automatically handles MIME types and multipart message creation, ensuring proper encoding and delivery of attachments.