> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/composiohq/composio/llms.txt
> Use this file to discover all available pages before exploring further.

# File Handling Example

> Learn how to handle file uploads and attachments with Composio tools

This example demonstrates how to use Composio tools that support file handling, such as sending emails with attachments using Gmail.

## Overview

In this example, you'll learn how to:

* Pass file paths to tools that support attachments
* Send emails with file attachments using Gmail
* Work with local file paths in tool arguments

## Prerequisites

<Steps>
  <Step title="Install dependencies">
    ```bash theme={null}
    npm install @composio/core dotenv
    ```
  </Step>

  <Step title="Set up environment variables">
    Create a `.env` file with your API key:

    ```bash theme={null}
    COMPOSIO_API_KEY=your_composio_api_key
    ```
  </Step>

  <Step title="Connect your Gmail account">
    Use Composio CLI to authenticate with Gmail:

    ```bash theme={null}
    composio add gmail
    ```

    This will open a browser window for OAuth authentication.
  </Step>
</Steps>

## Complete Example

```typescript theme={null}
import { Composio } from '@composio/core';
import 'dotenv/config';
import path from 'path';

/**
 * Initialize Composio
 */
const composio = new Composio({
  apiKey: process.env.COMPOSIO_API_KEY,
});

/**
 * Main function to run the example
 */
async function main() {
  try {
    console.log('🚀 Starting File-handling Example...');

    // Get available tools
    const tools = await composio.tools.get('default', 'GMAIL_SEND_EMAIL');

    console.log(`✅ Found ${tools.length} tools`);

    const filePath = path.join(__dirname, '..', 'pepe-silvia.png');
    console.log(`Sending file from ${filePath}`);

    const result = await composio.tools.execute('GMAIL_SEND_EMAIL', {
      userId: 'default',
      arguments: {
        attachment: filePath,
        recipient_email: 'musthaq@composio.dev',
        user_id: 'me',
        body: 'Hello, this is a test email with a file attachment.',
        subject: 'Test Email with Attachment',
      },
    });

    console.log(result);
  } catch (error) {
    console.error('❌ Error running example:', error);
  }
}

// Run the example
main().catch(console.error);
```

## How It Works

<Steps>
  <Step title="Initialize Composio">
    Create a Composio instance with your API key.
  </Step>

  <Step title="Fetch Gmail Tool">
    Get the `GMAIL_SEND_EMAIL` tool which supports file attachments.
  </Step>

  <Step title="Prepare File Path">
    Use Node's `path` module to construct the absolute path to your file. Composio handles reading and encoding the file.
  </Step>

  <Step title="Execute with Attachment">
    Pass the file path in the `attachment` parameter. Composio automatically:

    * Reads the file from the filesystem
    * Encodes it appropriately (base64 for email)
    * Includes it in the API request
  </Step>
</Steps>

## Tool Parameters

<ParamField path="attachment" type="string">
  Absolute or relative file path to the attachment
</ParamField>

<ParamField path="recipient_email" type="string" required>
  Email address of the recipient
</ParamField>

<ParamField path="subject" type="string" required>
  Email subject line
</ParamField>

<ParamField path="body" type="string" required>
  Email body content (plain text or HTML)
</ParamField>

<ParamField path="user_id" type="string">
  Gmail user ID (use 'me' for authenticated user)
</ParamField>

## Expected Output

```bash theme={null}
🚀 Starting File-handling Example...
✅ Found 1 tools
Sending file from /path/to/project/pepe-silvia.png
{
  successful: true,
  data: {
    id: '18d1234567890abcd',
    threadId: '18d1234567890abcd',
    labelIds: ['SENT']
  },
  error: null
}
```

## Supported File Types

Composio automatically handles various file types based on the tool:

<AccordionGroup>
  <Accordion title="Email Attachments (Gmail, Outlook)">
    * Images: `.png`, `.jpg`, `.jpeg`, `.gif`, `.bmp`
    * Documents: `.pdf`, `.doc`, `.docx`, `.txt`
    * Spreadsheets: `.xls`, `.xlsx`, `.csv`
    * Presentations: `.ppt`, `.pptx`
    * Archives: `.zip`, `.tar`, `.gz`
  </Accordion>

  <Accordion title="File Upload Tools (Drive, Dropbox)">
    All file types are supported. The tool will preserve the original file format and metadata.
  </Accordion>

  <Accordion title="Image Processing Tools">
    Specific image formats depending on the tool (typically `.png`, `.jpg`, `.jpeg`, `.webp`)
  </Accordion>
</AccordionGroup>

## Multiple Attachments

Some tools support multiple attachments. Check the tool schema:

```typescript theme={null}
const result = await composio.tools.execute('GMAIL_SEND_EMAIL', {
  userId: 'default',
  arguments: {
    attachments: [
      path.join(__dirname, 'file1.pdf'),
      path.join(__dirname, 'file2.png'),
    ],
    recipient_email: 'user@example.com',
    subject: 'Multiple Attachments',
    body: 'Email with multiple files',
  },
});
```

## URL-Based File Handling

You can also pass URLs for some tools:

```typescript theme={null}
const result = await composio.tools.execute('GMAIL_SEND_EMAIL', {
  userId: 'default',
  arguments: {
    attachment: 'https://example.com/document.pdf',
    recipient_email: 'user@example.com',
    subject: 'Document from URL',
    body: 'Attached document from URL',
  },
});
```

## Error Handling

<CodeGroup>
  ```typescript File Not Found theme={null}
  try {
    const result = await composio.tools.execute('GMAIL_SEND_EMAIL', {
      userId: 'default',
      arguments: {
        attachment: '/nonexistent/file.pdf',
        // ... other params
      },
    });
  } catch (error) {
    console.error('File not found:', error.message);
  }
  ```

  ```typescript File Too Large theme={null}
  try {
    const result = await composio.tools.execute('GMAIL_SEND_EMAIL', {
      userId: 'default',
      arguments: {
        attachment: '/path/to/large-file.zip', // > 25MB for Gmail
        // ... other params
      },
    });
  } catch (error) {
    console.error('File size limit exceeded:', error.message);
  }
  ```
</CodeGroup>

## Best Practices

<Check>**Use Absolute Paths**: Always use absolute paths or resolve relative paths using `path.join()` or `path.resolve()`</Check>

<Check>**Check File Size**: Be aware of size limits for different services (e.g., Gmail has a 25MB limit)</Check>

<Check>**Validate File Exists**: Check if the file exists before attempting to send it</Check>

<Check>**Handle Errors**: Always wrap file operations in try-catch blocks to handle missing files or permission errors</Check>

## Next Steps

<CardGroup cols={2}>
  <Card title="Custom Tools" icon="wrench" href="/examples/typescript/custom-tools">
    Create custom tools with file handling
  </Card>

  <Card title="OpenAI Example" icon="brain" href="/examples/typescript/openai-basic">
    Combine file handling with AI agents
  </Card>
</CardGroup>
