Skip to main content
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

1

Install dependencies

npm install @composio/core dotenv
2

Set up environment variables

Create a .env file with your API key:
COMPOSIO_API_KEY=your_composio_api_key
3

Connect your Gmail account

Use Composio CLI to authenticate with Gmail:
composio add gmail
This will open a browser window for OAuth authentication.

Complete Example

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: '[email protected]',
        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

1

Initialize Composio

Create a Composio instance with your API key.
2

Fetch Gmail Tool

Get the GMAIL_SEND_EMAIL tool which supports file attachments.
3

Prepare File Path

Use Node’s path module to construct the absolute path to your file. Composio handles reading and encoding the file.
4

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

Tool Parameters

attachment
string
Absolute or relative file path to the attachment
recipient_email
string
required
Email address of the recipient
subject
string
required
Email subject line
body
string
required
Email body content (plain text or HTML)
user_id
string
Gmail user ID (use ‘me’ for authenticated user)

Expected Output

🚀 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:
  • Images: .png, .jpg, .jpeg, .gif, .bmp
  • Documents: .pdf, .doc, .docx, .txt
  • Spreadsheets: .xls, .xlsx, .csv
  • Presentations: .ppt, .pptx
  • Archives: .zip, .tar, .gz
All file types are supported. The tool will preserve the original file format and metadata.
Specific image formats depending on the tool (typically .png, .jpg, .jpeg, .webp)

Multiple Attachments

Some tools support multiple attachments. Check the tool schema:
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: '[email protected]',
    subject: 'Multiple Attachments',
    body: 'Email with multiple files',
  },
});

URL-Based File Handling

You can also pass URLs for some tools:
const result = await composio.tools.execute('GMAIL_SEND_EMAIL', {
  userId: 'default',
  arguments: {
    attachment: 'https://example.com/document.pdf',
    recipient_email: '[email protected]',
    subject: 'Document from URL',
    body: 'Attached document from URL',
  },
});

Error Handling

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);
}

Best Practices

Use Absolute Paths: Always use absolute paths or resolve relative paths using path.join() or path.resolve()
Check File Size: Be aware of size limits for different services (e.g., Gmail has a 25MB limit)
Validate File Exists: Check if the file exists before attempting to send it
Handle Errors: Always wrap file operations in try-catch blocks to handle missing files or permission errors

Next Steps

Custom Tools

Create custom tools with file handling

OpenAI Example

Combine file handling with AI agents

Build docs developers (and LLMs) love