> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mail.ugmail.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Send Email from AI Agents Using UGMail SMTP and IMAP

> Give your AI agent its own dedicated email address using UGMail. Provision a mailbox via the API and connect your agent over SMTP in minutes.

AI agents increasingly need to interact with the outside world through email — sending task completion notifications, triggering follow-up workflows, or parsing replies to drive the next action. UGMail makes it straightforward to give each agent its own dedicated mailbox with a real email address, so your agents can send and receive email just like a human user would. Because UGMail charges no per-mailbox fees, you can provision a unique address for every agent in your fleet without worrying about cost.

## Prerequisites

* Your domain is [set up and DNS-verified](/guides/setup-domain) in UGMail
* A valid Bearer token from **Settings → API Connection** at [my.ugmail.co](https://my.ugmail.co)
* Python 3.7+ (for the examples below)

<Steps>
  <Step title="Create a dedicated mailbox for the agent">
    Provision a mailbox for your agent using the Management API. Give it a descriptive address that identifies the agent's role or identity.

    ```bash theme={null}
    curl -X POST "https://mail.ugmail.co/api/principal" \
      -H "Authorization: Bearer YOUR_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "ai-agent@example.com",
        "type": "individual",
        "secrets": ["AgentPassword123!"],
        "emails": ["ai-agent@example.com"]
      }'
    ```

    Store the agent's password securely in your application's secrets manager or environment variables — your agent code will need it at runtime.
  </Step>

  <Step title="Connect the agent via SMTP to send email">
    Use Python's built-in `smtplib` library to send email from your agent. The example below wraps the SMTP logic in a reusable function you can call from anywhere in your agent's code.

    ```python theme={null}
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart

    def send_agent_email(to_addr: str, subject: str, body: str):
        msg = MIMEMultipart()
        msg['From'] = 'ai-agent@example.com'
        msg['To'] = to_addr
        msg['Subject'] = subject
        msg.attach(MIMEText(body, 'plain'))

        with smtplib.SMTP('mail.ugmail.co', 587) as smtp:
            smtp.starttls()
            smtp.login('ai-agent@example.com', 'AgentPassword123!')
            smtp.send_message(msg)

    send_agent_email('user@example.com', 'Task Complete', 'Your report is ready.')
    ```

    UGMail's SMTP server listens on port `587` with STARTTLS. Always call `smtp.starttls()` before authenticating to ensure credentials are never sent in plaintext.
  </Step>

  <Step title="Read replies via IMAP">
    If your agent needs to act on email replies — for example, to continue a conversation, parse an approval, or trigger a downstream workflow — connect to UGMail's IMAP server and poll the inbox for unseen messages.

    ```python theme={null}
    import imaplib
    import email

    def check_agent_inbox():
        with imaplib.IMAP4_SSL('mail.ugmail.co', 993) as imap:
            imap.login('ai-agent@example.com', 'AgentPassword123!')
            imap.select('INBOX')
            _, messages = imap.search(None, 'UNSEEN')
            for num in messages[0].split():
                _, data = imap.fetch(num, '(RFC822)')
                msg = email.message_from_bytes(data[0][1])
                print(f'From: {msg["From"]}, Subject: {msg["Subject"]}')
    ```

    IMAP runs on port `993` with SSL/TLS — `imaplib.IMAP4_SSL` handles the secure connection automatically. Call `check_agent_inbox()` on a schedule (e.g., every 30 seconds) or integrate it into your agent's event loop to process replies as they arrive.
  </Step>
</Steps>

<Tip>
  Consider generating a unique, high-entropy password for each agent mailbox rather than reusing passwords across agents. Store each password in your secrets manager (e.g., AWS Secrets Manager, HashiCorp Vault, or a `.env` file that is never committed to source control). This way, if one agent is compromised, you can rotate just its credentials without affecting others.
</Tip>

<Note>
  Send responsibly. Even with unlimited mailboxes, email providers judge your domain's reputation based on sending patterns. Avoid sending bulk email from agent addresses — use dedicated transactional email infrastructure for high-volume sends, and reserve your agent mailboxes for low-volume, genuinely transactional messages. Respect bounce signals and unsubscribe requests to protect your domain's deliverability.
</Note>

## Connection settings reference

| Protocol         | Host             | Port  | Security |
| ---------------- | ---------------- | ----- | -------- |
| SMTP (sending)   | `mail.ugmail.co` | `587` | STARTTLS |
| IMAP (receiving) | `mail.ugmail.co` | `993` | SSL/TLS  |

## Next steps

<CardGroup cols={2}>
  <Card title="SaaS Onboarding" icon="users" href="/guides/saas-onboarding">
    Automatically provision a mailbox for every new user during sign-up.
  </Card>

  <Card title="Manage Aliases" icon="at" href="/guides/manage-aliases">
    Route multiple addresses to a single agent inbox using aliases.
  </Card>
</CardGroup>
