0PricingLogin
AI Agents · Lesson

Reading and Sending Emails Programmatically

Listing messages, getting message body, and sending MIME emails.

Listing Messages with the Gmail API

The first step in reading email is listing messages that match your criteria. service.users().messages().list() returns message IDs and thread IDs — not the full content. You then fetch each message individually. This two-step pattern keeps the list call fast.

def list_messages(service, user_id='me', query='', max_results=10):
    results = service.users().messages().list(
        userId=user_id,
        q=query,          # Gmail search query
        maxResults=max_results
    ).execute()

    messages = results.get('messages', [])
    print(f'Found {len(messages)} messages')
    return messages

# Examples of Gmail search queries:
# 'is:unread' — unread messages
# 'from:boss@company.com is:unread' — unread from boss
# 'subject:invoice label:inbox' — invoices in inbox
# 'after:2026/05/01 has:attachment' — recent with attachments
messages = list_messages(gmail_service, query='is:unread label:inbox')

Fetching a Full Message

Use service.users().messages().get() to retrieve the full message content. The format parameter controls how much data is returned: 'full' includes headers and body, 'metadata' returns only headers, 'minimal' returns just IDs and labels.

def get_message(service, message_id, user_id='me'):
    message = service.users().messages().get(
        userId=user_id,
        id=message_id,
        format='full'  # 'full', 'metadata', or 'minimal'
    ).execute()
    return message

# Fetch the first unread message
messages = list_messages(gmail_service, query='is:unread', max_results=1)
if messages:
    msg = get_message(gmail_service, messages[0]['id'])
    print('Thread ID:', msg['threadId'])
    print('Labels:', msg['labelIds'])
    print('Snippet:', msg['snippet'][:100])

All lessons in this course

  1. Connecting to Gmail via the API
  2. Reading and Sending Emails Programmatically
  3. Calendar Event Creation and Querying
  4. Building a Simple Email Assistant Agent
← Back to AI Agents