### EVM Quickstart: Setup and Create Inbox Source: https://docs.agentmail.to/integrations/x402 Set up the x402 client with an EVM signer and create an AgentMail inbox. This example demonstrates initializing the x402 client and the AgentMail client with x402 support, then creating a new inbox. ```typescript import { privateKeyToAccount } from "viem/accounts"; import { x402Client } from "@x402/fetch"; import { ExactEvmScheme } from "@x402/evm/exact/client"; import { AgentMailClient } from "agentmail"; // setup x402 client const PRIVATE_KEY = "0x..."; const signer = privateKeyToAccount(PRIVATE_KEY); const x402 = new x402Client(); x402.register("eip155:*", new ExactEvmScheme(signer)); // setup AgentMail client export const client = new AgentMailClient({ x402 }); // create inbox const inboxRes = await client.inboxes.create({ username: `x402-${Date.now()}`, }); console.log("Created inbox: ", inboxRes.inboxId); // subscribe to inbox const socket = await client.websockets.connect(); console.log("Connected to websocket"); socket.on("message", async (event) => { if (event.type === "subscribed") { console.log("Subscribed to", event.inboxIds); } else if (event.type === "event" && event.eventType === "message.received") { console.log("Received message from: ", event.message.from); } }); socket.sendSubscribe({ type: "subscribe", inboxIds: [inboxRes.inboxId], }); ``` -------------------------------- ### Solana Quickstart: Setup and Create Inbox Source: https://docs.agentmail.to/integrations/x402 Set up the x402 client with a Solana signer and create an AgentMail inbox. This example demonstrates initializing the x402 client and the AgentMail client with x402 support, then creating a new inbox. ```typescript import { createKeyPairSignerFromBytes } from "@solana/kit"; import { base58 } from "@scure/base"; import { x402Client } from "@x402/fetch"; import { ExactSvmClient, toClientSvmSigner } from "@x402/svm"; import { AgentMailClient } from "agentmail"; // setup x402 client const PRIVATE_KEY = "base58-encoded-private-key..."; const keypair = await createKeyPairSignerFromBytes( base58.decode(PRIVATE_KEY) ); const x402 = new x402Client(); x402.register("solana:*", new ExactSvmClient(toClientSvmSigner(keypair))); // setup AgentMail client export const client = new AgentMailClient({ x402 }); // create inbox const inboxRes = await client.inboxes.create({ username: `x402-${Date.now()}`, }); console.log("Created inbox: ", inboxRes.inboxId); // subscribe to inbox const socket = await client.websockets.connect(); console.log("Connected to websocket"); socket.on("message", async (event) => { if (event.type === "subscribed") { console.log("Subscribed to", event.inboxIds); } else if (event.type === "event" && event.eventType === "message.received") { console.log("Received message from: ", event.message.from); } }); socket.sendSubscribe({ type: "subscribe", inboxIds: [inboxRes.inboxId], }); ``` -------------------------------- ### Install Dependencies and Run Server Source: https://docs.agentmail.to/webhook-verification Commands to install necessary packages and start the webhook server for both Python and TypeScript. ```bash pip install flask python-dotenv svix python webhook_server.py ``` ```bash npm install express svix dotenv npx ts-node webhook_server.ts ``` -------------------------------- ### Agent Output Example Bash Source: https://docs.agentmail.to/documentation/examples/auto-reply-agent Example output shown in the terminal when the agent starts successfully. ```bash ============================================================ AUTO-REPLY EMAIL AGENT ============================================================ Setting up AgentMail infrastructure... ✓ Inbox created: auto-reply@agentmail.to ✓ Webhook created ✓ Setup complete! Inbox: auto-reply@agentmail.to Webhook: https://your-name.ngrok-free.app/webhook/agentmail Agent is ready! Send emails to: auto-reply@agentmail.to Reply mode: Template-based Waiting for incoming emails... * Running on http://127.0.0.1:8080 ``` -------------------------------- ### Agent Startup Console Output (Text) Source: https://docs.agentmail.to/sales-agent-websocket Example of the expected console output when the sales agent successfully starts and connects to the WebSocket. ```text Sales Agent starting... Inbox: sales-agent@agentmail.to ✓ Connecting to AgentMail WebSocket... ✓ Connected! Listening for emails... ✓ Subscribed to: ['sales-agent@agentmail.to'] ``` -------------------------------- ### Python WebSocket Quickstart Source: https://docs.agentmail.to/websockets/quickstart Connect to AgentMail WebSockets, subscribe to an inbox, and process incoming messages. Ensure you have the agentmail library installed. ```python from agentmail import AgentMail, Subscribe, Subscribed, MessageReceivedEvent client = AgentMail() with client.websockets.connect() as socket: socket.send_subscribe(Subscribe(inbox_ids=["my-agent@agentmail.to"])) for event in socket: if isinstance(event, Subscribed): print(f"Subscribed to {event.inbox_ids}") elif isinstance(event, MessageReceivedEvent): print(f"Received from: {event.message.from_}") ``` -------------------------------- ### TypeScript WebSocket Quickstart Source: https://docs.agentmail.to/websockets/quickstart Connect to AgentMail WebSockets, subscribe to an inbox, and handle incoming messages. Ensure you have the agentmail library installed. ```typescript import { AgentMailClient } from "agentmail"; const client = new AgentMailClient(); const socket = await client.websockets.connect(); socket.on("message", async (e) => { if (e.type === "subscribed") console.log("Subscribed to", e.inboxIds); else if (e.type === "event" && e.eventType === "message.received") console.log("Received from:", e.message?.from); }); await socket.waitForOpen(); socket.sendSubscribe({ type: "subscribe", inboxIds: ["my-agent@agentmail.to"] }); ``` -------------------------------- ### AgentMail Drafts API Reference and Examples Source: https://docs.agentmail.to/drafts Comprehensive examples for managing drafts, including creation, sending, scheduling, and updating. Requires setup with the AgentMail SDK and API key. Supports both immediate sending and scheduled delivery. ```python """ AgentMail Drafts — copy into Cursor/Claude. Setup: pip install agentmail python-dotenv. Set AGENTMAIL_API_KEY in .env. API reference: - inboxes.drafts.create(inbox_id, to, subject?, text?, html?, cc?, bcc?, reply_to?, attachments?, send_at?) - inboxes.drafts.get(inbox_id, draft_id) - inboxes.drafts.update(inbox_id, draft_id, to?, subject?, text?, html?, send_at?, ...) - inboxes.drafts.send(inbox_id, draft_id) — converts to Message, deletes draft - inboxes.drafts.delete(inbox_id, draft_id) - inboxes.drafts.list(inbox_id, limit?, page_token?, labels?) - drafts.list(limit?, page_token?) — org-wide Scheduled sending: pass send_at (ISO 8601 datetime) to create() or update(). Draft is auto-labeled 'scheduled' and sent at the specified time. send_status: 'scheduled' | 'sending' | 'failed'. Cancel by deleting the draft. Reschedule by updating send_at. Errors: SDK raises on 4xx/5xx. Rate limit: 429 with Retry-After. """ import os from datetime import datetime, timedelta from dotenv import load_dotenv from agentmail import AgentMail load_dotenv() client = AgentMail(api_key=os.getenv("AGENTMAIL_API_KEY")) inbox_id = "agent@agentmail.to" # Create and send immediately draft = client.inboxes.drafts.create(inbox_id, to=["review@example.com"], subject="[REVIEW] Proposed reply") sent = client.inboxes.drafts.send(inbox_id, draft.draft_id) print(sent.message_id) # Schedule for later send_time = (datetime.utcnow() + timedelta(days=1)).replace(hour=9, minute=0, second=0) scheduled = client.inboxes.drafts.create( inbox_id, to=["prospect@example.com"], subject="Follow up", text="Just following up...", send_at=send_time.isoformat() + "Z" ) print(f"Scheduled for {scheduled.send_at}, status: {scheduled.send_status}") all_drafts = client.drafts.list() ``` ```typescript """ AgentMail Drafts — copy into Cursor/Claude. Setup: npm install agentmail dotenv. Set AGENTMAIL_API_KEY in .env. API reference: - inboxes.drafts.create(inboxId, { to, subject?, text?, html?, cc?, bcc?, replyTo?, attachments?, sendAt? }) - inboxes.drafts.get(inboxId, draftId) - inboxes.drafts.update(inboxId, draftId, { to?, subject?, text?, html?, sendAt?, ... }) - inboxes.drafts.send(inboxId, draftId) — converts to Message, deletes draft - inboxes.drafts.delete(inboxId, draftId) - inboxes.drafts.list(inboxId, { limit?, pageToken?, labels? }) - drafts.list({ limit?, pageToken? }) — org-wide Scheduled sending: pass sendAt (ISO 8601 datetime) to create() or update(). Draft is auto-labeled 'scheduled' and sent at the specified time. sendStatus: 'scheduled' | 'sending' | 'failed'. Cancel by deleting the draft. Reschedule by updating sendAt. Errors: SDK throws on 4xx/5xx. Rate limit: 429 with Retry-After. """ import { AgentMailClient } from "agentmail"; import "dotenv/config"; const client = new AgentMailClient({ apiKey: process.env.AGENTMAIL_API_KEY! }); async function main() { const inboxId = "agent@agentmail.to"; // Create and send immediately const draft = await client.inboxes.drafts.create(inboxId, { to: ["review@example.com"], subject: "[REVIEW] Proposed reply", }); const sent = await client.inboxes.drafts.send(inboxId, draft.draftId); console.log(sent.messageId); // Schedule for later const sendTime = new Date(); sendTime.setUTCDate(sendTime.getUTCDate() + 1); sendTime.setUTCHours(9, 0, 0, 0); const scheduled = await client.inboxes.drafts.create(inboxId, { to: ["prospect@example.com"], subject: "Follow up", text: "Just following up...", sendAt: sendTime.toISOString(), }); console.log(`Scheduled for ${scheduled.sendAt}, status: ${scheduled.sendStatus}`); const allDrafts = await client.drafts.list(); } main(); ``` -------------------------------- ### TypeScript SDK Reference Source: https://docs.agentmail.to/threads TypeScript SDK methods for interacting with the AgentMail Threads API. Includes setup instructions and examples for listing, getting, and deleting threads. ```APIDOC ## AgentMail Threads API (TypeScript SDK) ### Setup ```bash npm install agentmail dotenv ``` Set `AGENTMAIL_API_KEY` in your `.env` file. ### API Reference **Per-inbox Threads:** - `inboxes.threads.list(inboxId, { limit?, pageToken?, labels?, before?, after?, ascending? })` - Lists threads within a specific inbox. - `inboxes.threads.get(inboxId, threadId)` - Retrieves a specific thread from an inbox. - `inboxes.threads.getAttachment(inboxId, threadId, attachmentId)` - Retrieves an attachment from a specific thread in an inbox. - `inboxes.threads.delete(inboxId, threadId)` - Deletes a specific thread from an inbox. **Organization-wide Threads:** - `threads.list({ limit?, pageToken?, labels? })` - Lists all threads across all inboxes in the organization. - `threads.get(threadId)` - Retrieves a specific thread organization-wide. - `threads.getAttachment(threadId, attachmentId)` - Retrieves an attachment from a specific thread organization-wide. ### Error Handling - The SDK throws exceptions for 4xx/5xx HTTP errors. - Rate limiting is indicated by a 429 status code with a `Retry-After` header. ``` -------------------------------- ### Python SDK Reference Source: https://docs.agentmail.to/threads Python SDK methods for interacting with the AgentMail Threads API. Includes setup instructions and examples for listing, getting, and deleting threads. ```APIDOC ## AgentMail Threads API (Python SDK) ### Setup ```bash pip install agentmail python-dotenv ``` Set `AGENTMAIL_API_KEY` in your `.env` file. ### API Reference **Per-inbox Threads:** - `inboxes.threads.list(inbox_id, limit?, page_token?, labels?, before?, after?, ascending?)` - Lists threads within a specific inbox. - `inboxes.threads.get(inbox_id, thread_id)` - Retrieves a specific thread from an inbox. - `inboxes.threads.get_attachment(inbox_id, thread_id, attachment_id)` - Retrieves an attachment from a specific thread in an inbox. - `inboxes.threads.delete(inbox_id, thread_id)` - Deletes a specific thread from an inbox. **Organization-wide Threads:** - `threads.list(limit?, page_token?, labels?)` - Lists all threads across all inboxes in the organization. - `threads.get(thread_id)` - Retrieves a specific thread organization-wide. - `threads.get_attachment(thread_id, attachment_id)` - Retrieves an attachment from a specific thread organization-wide. ### Error Handling - The SDK raises exceptions for 4xx/5xx HTTP errors. - Rate limiting is indicated by a 429 status code with a `Retry-After` header. ``` -------------------------------- ### TypeScript Messages API Example Source: https://docs.agentmail.to/messages Shows how to use the AgentMail TypeScript SDK to send, list, get, and reply to messages. Requires npm installation of agentmail and dotenv, and AGENTMAIL_API_KEY in .env. ```typescript import { AgentMailClient } from "agentmail"; import "dotenv/config"; const client = new AgentMailClient({ apiKey: process.env.AGENTMAIL_API_KEY! }); async function main() { const inboxId = "agent@agentmail.to"; const sent = await client.inboxes.messages.send(inboxId, { to: "user@example.com", subject: "Hi", text: "Body", labels: ["outreach"], }); console.log(sent.messageId, sent.threadId); const res = await client.inboxes.messages.list(inboxId, { limit: 10 }); for (const msg of res.messages) { const content = msg.extractedText ?? msg.text; } const msg = await client.inboxes.messages.get(inboxId, res.messages[0].messageId); await client.inboxes.messages.reply(inboxId, msg.messageId, { text: "Thanks!" }); } main(); ``` -------------------------------- ### Python Quickstart Source: https://docs.agentmail.to/quickstart This Python code snippet demonstrates how to set up the AgentMail SDK, create an inbox, send a message, and list received messages. It includes error handling and idempotency guidance. ```APIDOC ## AgentMail Python Quickstart ### Description This Python code snippet demonstrates how to set up the AgentMail SDK, create an inbox, send a message, and list received messages. It includes error handling and idempotency guidance. ### Setup 1. Install the SDK: `pip install agentmail python-dotenv` 2. Set your API key: Create a `.env` file with `AGENTMAIL_API_KEY='your_api_key'`. ### Agent Sign-up (No API Key Needed) - `agent.sign_up(human_email, username)`: Returns `api_key`, `inbox_id`, `organization_id`. - `agent.verify(otp_code)`: Verifies with OTP sent to `human_email`. ### API Reference - **Inboxes:** - `client.inboxes.create(username?, domain?, display_name?, client_id?)`: Creates a new inbox. `client_id` is used for idempotent retries. - **Messages:** - `client.inboxes.messages.send(inbox_id, to, subject, text, html?, cc?, bcc?, reply_to?, attachments?)`: Sends an email message. - `client.inboxes.messages.list(inbox_id, limit?, page_token?, labels?)`: Retrieves a list of messages. Use `extracted_text` or `extracted_html` for reply content. ### Error Handling The SDK raises exceptions for 4xx and 5xx errors. Inspect `error.body.message` or `str(e)` for details. ### Rate Limiting Responses with a 429 status code include a `Retry-After` header. Implement exponential backoff for retries. ### Idempotency Pass a unique `client_id` to `inboxes.create()` to ensure safe retries without creating duplicate inboxes. ``` -------------------------------- ### Python Messages API Example Source: https://docs.agentmail.to/messages Demonstrates sending, listing, getting, and replying to messages using the AgentMail Python SDK. Ensure AGENTMAIL_API_KEY is set in your .env file and install the required libraries. ```python import os from dotenv import load_dotenv from agentmail import AgentMail load_dotenv() client = AgentMail(api_key=os.getenv("AGENTMAIL_API_KEY")) inbox_id = "agent@agentmail.to" # Send sent = client.inboxes.messages.send(inbox_id, to="user@example.com", subject="Hi", text="Body", labels=["outreach"]) print(sent.message_id, sent.thread_id) # List, get res = client.inboxes.messages.list(inbox_id, limit=10) for msg in res.messages: content = msg.extracted_text or msg.text msg = client.inboxes.messages.get(inbox_id, res.messages[0].message_id) # Reply reply = client.inboxes.messages.reply(inbox_id, msg.message_id, text="Thanks!") ``` -------------------------------- ### Sign Up Agent via HTTP POST (Swift) Source: https://docs.agentmail.to/api-reference/agent/sign-up Implement agent sign-up in Swift using URLSession. This example details setting up the HTTP request, headers, and body for the POST request. ```swift import Foundation let headers = ["Content-Type": "application/json"] let parameters = [ "human_email": "human_email", "username": "username" ] as [String : Any] let postData = JSONSerialization.data(withJSONObject: parameters, options: []) let request = NSMutableURLRequest(url: NSURL(string: "https://api.agentmail.to/v0/agent/sign-up")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData as Data let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error as Any) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) dataTask.resume() ``` -------------------------------- ### Run Python Quickstart Script Source: https://docs.agentmail.to/quickstart Execute the Python quickstart script from your terminal to create an inbox and send an email. ```bash python quickstart.py ``` -------------------------------- ### Get Attachment using Python SDK Source: https://docs.agentmail.to/api-reference/drafts/get-attachment Example of how to get a draft attachment using the AgentMail Python SDK. ```APIDOC ## Get Attachment ### Description Retrieves a specific attachment from a draft. ### Method `get_attachment(draft_id: str, attachment_id: str)` ### Parameters #### Path Parameters - **draft_id** (str) - Required - The ID of the draft. - **attachment_id** (str) - Required - The ID of the attachment. ### SDK Usage ```python from agentmail import AgentMail client = AgentMail( api_key="YOUR_TOKEN_HERE", ) client.drafts.get_attachment( draft_id="draft_id", attachment_id="attachment_id", ) ``` ``` -------------------------------- ### Create Project Directory Source: https://docs.agentmail.to/documentation/examples/auto-reply-agent Create a new directory for your agent and navigate into it. ```bash mkdir auto-reply-agent cd auto-reply-agent ``` -------------------------------- ### Get Attachment using AgentMail SDK Source: https://docs.agentmail.to/api-reference/drafts/get-attachment Example of how to get a draft attachment using the AgentMail TypeScript SDK. ```APIDOC ## Get Attachment ### Description Retrieves a specific attachment from a draft. ### Method `getAttachment(draftId: string, attachmentId: string): Promise` ### Parameters #### Path Parameters - **draft_id** (string) - Required - The ID of the draft. - **attachment_id** (string) - Required - The ID of the attachment. ### SDK Usage ```typescript import { AgentMailClient } from "agentmail"; async function main() { const client = new AgentMailClient({ apiKey: "YOUR_TOKEN_HERE", }); await client.drafts.getAttachment("draft_id", "attachment_id"); } main(); ``` ``` -------------------------------- ### Create Project Directory Source: https://docs.agentmail.to/documentation/examples/smart-labeling-agent Set up a new directory for your smart labeling agent project. This is the initial step before adding any code. ```bash mkdir smart-labeling-agent cd smart-labeling-agent ``` -------------------------------- ### TypeScript Quickstart Source: https://docs.agentmail.to/quickstart This TypeScript code snippet shows how to use the AgentMail SDK, including setting up the client, creating an inbox, sending an email, and fetching messages. It also covers error handling and idempotency. ```APIDOC ## AgentMail TypeScript Quickstart ### Description This TypeScript code snippet demonstrates how to set up the AgentMail SDK, create an inbox, send a message, and list received messages. It includes error handling and idempotency guidance. ### Setup 1. Install the SDK: `npm install agentmail dotenv` 2. Set your API key: Create a `.env` file with `AGENTMAIL_API_KEY='your_api_key'`. ### Agent Sign-up (No API Key Needed) - `agent.signUp({ humanEmail, username })`: Returns `apiKey`, `inboxId`, `organizationId`. - `agent.verify({ otpCode })`: Verifies with OTP sent to `humanEmail`. ### API Reference - **Inboxes:** - `client.inboxes.create({ username?, domain?, displayName?, clientId? })`: Creates a new inbox. `clientId` is used for idempotent retries. - **Messages:** - `client.inboxes.messages.send(inboxId, { to, subject, text, html?, cc?, bcc?, replyTo?, attachments? })`: Sends an email message. - `client.inboxes.messages.list(inboxId, { limit?, pageToken?, labels? })`: Retrieves a list of messages. Use `extractedText` or `extractedHtml` for reply content. ### Error Handling The SDK throws errors for 4xx and 5xx responses. Check `error.body?.message` for details. ### Rate Limiting Responses with a 429 status code include a `Retry-After` header. Implement exponential backoff for retries. ### Idempotency Pass a unique `clientId` to `inboxes.create()` to ensure safe retries without creating duplicate inboxes. ``` -------------------------------- ### Python AgentMail Quickstart Source: https://docs.agentmail.to/quickstart Use this Python snippet for a complete AgentMail integration. It includes setup instructions, API usage for creating inboxes and sending/receiving messages, and notes on error handling, rate limiting, and idempotency. ```python import os from dotenv import load_dotenv from agentmail import AgentMail load_dotenv() client = AgentMail(api_key=os.getenv("AGENTMAIL_API_KEY")) # create inbox (client_id enables safe retries) inbox = client.inboxes.create(client_id="my-agent-inbox-v1") # send email try: client.inboxes.messages.send( inbox.inbox_id, to="recipient@example.com", subject="Hello from AgentMail", text="Plain text body", html="

HTML body

", ) except Exception as e: # handle validation, not found, rate limit (429), etc. print(f"Send failed: {e}") raise # receive messages for msg in client.inboxes.messages.list(inbox.inbox_id, limit=10).messages: print(msg.subject, msg.extracted_text or msg.text) ``` -------------------------------- ### Get Attachment via HTTP Request (C#) Source: https://docs.agentmail.to/api-reference/drafts/get-attachment Use RestSharp in C# to get a draft attachment. This example illustrates setting the GET method and the authorization header. ```csharp using RestSharp; var client = new RestClient("https://api.agentmail.to/v0/drafts/draft_id/attachments/attachment_id"); var request = new RestRequest(Method.GET); request.AddHeader("Authorization", "Bearer "); IRestResponse response = client.Execute(request); ``` -------------------------------- ### Get Attachment using HTTP Request Source: https://docs.agentmail.to/api-reference/inboxes/messages/get-attachment Example of how to retrieve a message attachment by making a direct HTTP GET request to the AgentMail API. ```go package main import ( "fmt" "net/http" "io" ) func main() { url := "https://api.agentmail.to/v0/inboxes/inbox_id/messages/message_id/attachments/attachment_id" req, _ := http.NewRequest("GET", url, nil) req.Header.Add("Authorization", "Bearer ") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) } ``` ```ruby require 'uri' require 'net/http' url = URI("https://api.agentmail.to/v0/inboxes/inbox_id/messages/message_id/attachments/attachment_id") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Get.new(url) request["Authorization"] = 'Bearer ' response = http.request(request) puts response.read_body ``` ```java import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; HttpResponse response = Unirest.get("https://api.agentmail.to/v0/inboxes/inbox_id/messages/message_id/attachments/attachment_id") .header("Authorization", "Bearer ") .asString(); ``` ```php request('GET', 'https://api.agentmail.to/v0/inboxes/inbox_id/messages/message_id/attachments/attachment_id', [ 'headers' => [ 'Authorization' => 'Bearer ', ], ]); echo $response->getBody(); ``` ```csharp using RestSharp; var client = new RestClient("https://api.agentmail.to/v0/inboxes/inbox_id/messages/message_id/attachments/attachment_id"); var request = new RestRequest(Method.GET); request.AddHeader("Authorization", "Bearer "); IRestResponse response = client.Execute(request); ``` ```swift import Foundation let headers = ["Authorization": "Bearer "] let request = NSMutableURLRequest(url: NSURL(string: "https://api.agentmail.to/v0/inboxes/inbox_id/messages/message_id/attachments/attachment_id")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "GET" request.allHTTPHeaderFields = headers let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error as Any) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) dataTask.resume() ``` -------------------------------- ### Setup and Run Email Agent Source: https://docs.agentmail.to/documentation/examples/auto-reply-agent Initializes the agent's mailbox and listener, then starts the Flask application to listen for incoming emails. Requires `setup_agentmail` and `app.run` to be configured. ```python if __name__ == '__main__': print("\n" + "="*60) print("AUTO-REPLY EMAIL AGENT") print("="*60 + "\n") inbox, listener = setup_agentmail() print(f"Agent is ready!") print(f"Send emails to: {inbox.inbox_id}") print(f"\nWaiting for incoming emails...\n") app.run(port=PORT) ``` -------------------------------- ### Get Raw Message using AgentMail SDK (Python) Source: https://docs.agentmail.to/api-reference/inboxes/messages/get-raw Example of how to get the raw content of a message using the AgentMail Python SDK. ```python from agentmail import AgentMail client = AgentMail( api_key="YOUR_TOKEN_HERE", ) client.inboxes.messages.get_raw( inbox_id="inbox_id", message_id="message_id", ) ``` -------------------------------- ### Create Domain via HTTP POST (Swift) Source: https://docs.agentmail.to/api-reference/domains/create This Swift example demonstrates creating a domain by constructing and sending an HTTP POST request using URLSession. It shows how to set headers and the JSON body. ```swift import Foundation let headers = [ "Authorization": "Bearer ", "Content-Type": "application/json" ] let parameters = [ "domain": "domain", "feedback_enabled": true ] as [String : Any] let postData = JSONSerialization.data(withJSONObject: parameters, options: []) let request = NSMutableURLRequest(url: NSURL(string: "https://api.agentmail.to/v0/domains")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData as Data let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error as Any) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) dataTask.resume() ``` -------------------------------- ### Get Inbox via HTTP Request (Swift) Source: https://docs.agentmail.to/api-reference/pods/inboxes/get Make an HTTP GET request in Swift to get inbox details. This example uses URLSession and NSMutableURLRequest to set up the request with the necessary headers and URL. ```swift import Foundation let headers = ["Authorization": "Bearer "] let request = NSMutableURLRequest(url: NSURL(string: "https://api.agentmail.to/v0/pods/pod_id/inboxes/inbox_id")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "GET" request.allHTTPHeaderFields = headers let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error as Any) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) dataTask.resume() ``` -------------------------------- ### Get Inbox Details via HTTP GET Request (PHP) Source: https://docs.agentmail.to/api-reference/inboxes/get This PHP example shows how to get inbox details using Guzzle HTTP client. Include your API key in the Authorization header. ```php request('GET', 'https://api.agentmail.to/v0/inboxes/inbox_id', [ 'headers' => [ 'Authorization' => 'Bearer ', ], ]); echo $response->getBody(); ``` -------------------------------- ### Run TypeScript Quickstart Script Source: https://docs.agentmail.to/quickstart Execute the TypeScript quickstart script using ts-node to create an inbox and send an email. ```bash npx ts-node quickstart.ts ``` -------------------------------- ### Get Inbox Details via HTTP GET Request (Ruby) Source: https://docs.agentmail.to/api-reference/inboxes/get This Ruby example demonstrates fetching inbox details using a direct HTTP GET request. Ensure your API key is included in the Authorization header. ```ruby require 'uri' require 'net/http' url = URI("https://api.agentmail.to/v0/inboxes/inbox_id") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Get.new(url) request["Authorization"] = 'Bearer ' response = http.request(request) puts response.read_body ``` -------------------------------- ### Python Webhook Setup Source: https://docs.agentmail.to/webhook-setup Use this Python Flask example to set up a webhook receiver. It creates an inbox and a webhook, then defines a route to handle incoming POST requests. Ensure you replace YOUR_NGROK.ngrok-free.app with your actual ngrok URL. ```python """ AgentMail Webhook Setup — copy into Cursor/Claude. Flow: 1) ngrok http 3000 → copy URL. 2) inboxes.create(client_id=...) 3) webhooks.create(url=ngrok+/webhooks, event_types=[...], client_id=...) 4) Flask POST /webhooks: return 200 immediately, process request.json in background. Local: use http://127.0.0.1:3000 in browser, not ngrok URL. """ from flask import Flask, request, Response from agentmail import AgentMail app = Flask(__name__) client = AgentMail() inbox = client.inboxes.create(username="webhook-demo", client_id="webhook-demo-inbox") wh = client.webhooks.create(url="https://YOUR_NGROK.ngrok-free.app/webhooks", event_types=["message.received"], client_id="webhook-demo-webhook") @app.route("/webhooks", methods=["POST"]) def receive(): payload = request.json print(payload.get("event_type"), payload.get("message", {}).get("subject")) return Response(status=200) ``` -------------------------------- ### Install AgentMail Skill for a specific agent Source: https://docs.agentmail.to/integrations/skills To bypass interactive prompts, specify the skill and agent directly when installing. This example targets the 'agentmail' skill for the 'claude-code' agent. ```bash npx skills add agentmail-to/agentmail-skills --skill agentmail --agent claude-code ``` -------------------------------- ### Sign Up Agent via HTTP POST (C#) Source: https://docs.agentmail.to/api-reference/agent/sign-up Sign up an agent using C# with the RestSharp library. This example shows how to configure the REST client, request, headers, and body. ```csharp using RestSharp; var client = new RestClient("https://api.agentmail.to/v0/agent/sign-up"); var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", "{\n \"human_email\": \"human_email\",\n \"username\": \"username\"\n}", ParameterType.RequestBody); IRestResponse response = client.Execute(request); ``` -------------------------------- ### Get Attachment using URLSession (Swift) Source: https://docs.agentmail.to/api-reference/threads/get-attachment This Swift example demonstrates fetching an attachment using URLSession. It configures the request with the necessary headers and makes the GET call. ```swift import Foundation let headers = ["Authorization": "Bearer "] let request = NSMutableURLRequest(url: NSURL(string: "https://api.agentmail.to/v0/threads/thread_id/attachments/attachment_id")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "GET" request.allHTTPHeaderFields = headers let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error as Any) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) dataTask.resume() ``` -------------------------------- ### Create and Manage Pods with AgentMail SDK (Python) Source: https://docs.agentmail.to/changelog/2025/6/15 Demonstrates how to initialize the AgentMail client, create a new pod for a team, add an inbox to that pod, and list all existing pods in the organization. Ensure you have your API key ready for client initialization. ```python from agentmail import AgentMail client = AgentMail(api_key="your-api-key") # create a pod for your sales team pod = client.pods.create( name="Sales Team", description="Shared resources for sales agents" ) # create an inbox in the pod inbox = client.pods.inboxes.create( pod_id=pod.pod_id, inbox_id="sales@example.com" ) # list all pods pods = client.pods.list() for pod in pods.pods: print(f"Pod: {pod.name} ({len(pod.inbox_ids)} inboxes)") ``` -------------------------------- ### Get Attachment using HTTP Request (Ruby) Source: https://docs.agentmail.to/api-reference/inboxes/threads/get-attachment Fetch an attachment by making an HTTP GET request. This example demonstrates setting the Authorization header with your API key. ```ruby require 'uri' require 'net/http' url = URI("https://api.agentmail.to/v0/inboxes/inbox_id/threads/thread_id/attachments/attachment_id") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Get.new(url) request["Authorization"] = 'Bearer ' response = http.request(request) puts response.read_body ``` -------------------------------- ### Get Attachment using HTTP Request (Go) Source: https://docs.agentmail.to/api-reference/inboxes/threads/get-attachment Manually construct an HTTP GET request to retrieve an attachment. This example shows how to set the URL and authorization header. ```go package main import ( "fmt" "net/http" "io" ) func main() { url := "https://api.agentmail.to/v0/inboxes/inbox_id/threads/thread_id/attachments/attachment_id" req, _ := http.NewRequest("GET", url, nil) req.Header.Add("Authorization", "Bearer ") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) } ``` -------------------------------- ### Create Domain via HTTP POST (Go) Source: https://docs.agentmail.to/api-reference/domains/create This Go example demonstrates how to create a domain by making a direct HTTP POST request to the AgentMail API. It includes setting the necessary headers and payload. ```go package main import ( "fmt" "strings" "net/http" "io" ) func main() { url := "https://api.agentmail.to/v0/domains" payload := strings.NewReader("{\n \"domain\": \"domain\",\n \"feedback_enabled\": true\n}") req, _ := http.NewRequest("POST", url, payload) req.Header.Add("Authorization", "Bearer ") req.Header.Add("Content-Type", "application/json") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) } ``` -------------------------------- ### Create Pod via HTTP POST (Ruby) Source: https://docs.agentmail.to/api-reference/pods/create This Ruby example demonstrates how to make a direct HTTP POST request to create a pod, including setting the necessary Authorization and Content-Type headers. ```ruby require 'uri' require 'net/http' url = URI("https://api.agentmail.to/v0/pods") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Post.new(url) request["Authorization"] = 'Bearer ' request["Content-Type"] = 'application/json' request.body = "{}" response = http.request(request) puts response.read_body ``` -------------------------------- ### Get Inbox Details via HTTP GET Request (Go) Source: https://docs.agentmail.to/api-reference/inboxes/get Retrieve inbox details by making a direct HTTP GET request. This example uses Go's standard library and requires your API key in the Authorization header. ```go package main import ( "fmt" "net/http" "io" ) func main() { url := "https://api.agentmail.to/v0/inboxes/inbox_id" req, _ := http.NewRequest("GET", url, nil) req.Header.Add("Authorization", "Bearer ") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) } ``` -------------------------------- ### Get Thread by ID using HTTP Request (PHP) Source: https://docs.agentmail.to/api-reference/threads/get Fetch a thread by its ID with an HTTP GET request in PHP. This example uses GuzzleHttp to set the Authorization header. ```php request('GET', 'https://api.agentmail.to/v0/threads/thread_id', [ 'headers' => [ 'Authorization' => 'Bearer ', ], ]); echo $response->getBody(); ``` -------------------------------- ### Install Solana Dependencies for x402 Source: https://docs.agentmail.to/integrations/x402 Install the necessary npm packages for x402 integration with Solana wallets. ```bash npm install agentmail @x402/fetch @x402/svm @solana/kit @scure/base ``` -------------------------------- ### Sign Up, Create Inbox, and Send Email via CLI Source: https://docs.agentmail.to/agent-onboarding Command-line interface commands to sign up, verify, create an inbox, and send an email. Ensure you replace `` with the actual ID obtained after creation. ```Bash # sign up and verify agentmail agent sign-up --human-email you@example.com --username my-agent agentmail agent verify --otp-code 123456 # create an inbox agentmail inboxes create --display-name "My AI Agent" # send an email (replace with the id from above) agentmail inboxes:messages send \ --inbox-id \ --to user@example.com \ --subject "Hello from my AI agent" \ --text "Hi! I'm an AI agent with my own email address." ``` -------------------------------- ### Get Thread by ID using HTTP Request (Ruby) Source: https://docs.agentmail.to/api-reference/threads/get Access a thread by its ID via an HTTP GET request. This example shows how to set the Authorization header in Ruby. ```ruby require 'uri' require 'net/http' url = URI("https://api.agentmail.to/v0/threads/thread_id") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Get.new(url) request["Authorization"] = 'Bearer ' response = http.request(request) puts response.read_body ``` -------------------------------- ### Get Thread by ID using HTTP Request (Go) Source: https://docs.agentmail.to/api-reference/threads/get Retrieve a thread by its ID by making a direct HTTP GET request. This example demonstrates setting the Authorization header. ```go package main import ( "fmt" "net/http" "io" ) func main() { url := "https://api.agentmail.to/v0/threads/thread_id" req, _ := http.NewRequest("GET", url, nil) req.Header.Add("Authorization", "Bearer ") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) } ``` -------------------------------- ### Sign Up Agent via HTTP POST (Ruby) Source: https://docs.agentmail.to/api-reference/agent/sign-up Implement agent sign-up using Ruby by making a direct HTTP POST request. This involves setting up the URI, HTTP client, and request details. ```ruby require 'uri' require 'net/http' url = URI("https://api.agentmail.to/v0/agent/sign-up") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Post.new(url) request["Content-Type"] = 'application/json' request.body = "{\n \"human_email\": \"human_email\",\n \"username\": \"username\"\n}" response = http.request(request) puts response.read_body ``` -------------------------------- ### Create API Key via HTTP POST Request (Swift) Source: https://docs.agentmail.to/api-reference/api-keys/create This Swift example demonstrates creating an API key by making an HTTP POST request. It includes setting up URL requests, headers, and handling the response. ```swift import Foundation let headers = [ "Authorization": "Bearer ", "Content-Type": "application/json" ] let parameters = [] as [String : Any] let postData = JSONSerialization.data(withJSONObject: parameters, options: []) let request = NSMutableURLRequest(url: NSURL(string: "https://api.agentmail.to/v0/api-keys")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData as Data let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error as Any) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) dataTask.resume() ``` -------------------------------- ### Get List Data via HTTP Request (Go) Source: https://docs.agentmail.to/api-reference/lists/get Directly query the AgentMail API using an HTTP GET request. This example demonstrates setting the Authorization header. ```go package main import ( "fmt" "net/http" "io" ) func main() { url := "https://api.agentmail.to/v0/lists/send/allow/entry" req, _ := http.NewRequest("GET", url, nil) req.Header.Add("Authorization", "Bearer ") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) } ``` -------------------------------- ### TypeScript Webhook Setup Source: https://docs.agentmail.to/webhook-setup This TypeScript example using Express sets up a webhook receiver. It initializes the AgentMail client, creates an inbox and a webhook, and defines a POST route for handling incoming webhook events. Remember to replace YOUR_NGROK.ngrok-free.app with your ngrok URL. ```typescript """ AgentMail Webhook Setup — copy into Cursor/Claude. Flow: 1) ngrok http 3000. 2) inboxes.create({ clientId }). 3) webhooks.create({ url, eventTypes, clientId }) 4) Express POST /webhooks: res.status(200).send(), process req.body async. Use express.raw() if you add Svix verification later. """ import express from "express"; import { AgentMailClient } from "agentmail"; const client = new AgentMailClient({ apiKey: process.env.AGENTMAIL_API_KEY! }); const inbox = await client.inboxes.create({ username: "webhook-demo", clientId: "webhook-demo-inbox" }); await client.webhooks.create({ url: "https://YOUR_NGROK.ngrok-free.app/webhooks", eventTypes: ["message.received"], clientId: "webhook-demo-webhook", }); const app = express(); app.post("/webhooks", express.json(), (req, res) => { console.log(req.body.event_type, req.body.message?.subject); res.status(200).send(); }); app.listen(3000); ``` -------------------------------- ### Get Inbox Thread via HTTP Request (C#) Source: https://docs.agentmail.to/api-reference/inboxes/threads/get Use the RestSharp library in C# to make a GET request for a thread. This example includes setting the Authorization header. ```csharp using RestSharp; var client = new RestClient("https://api.agentmail.to/v0/inboxes/inbox_id/threads/thread_id"); var request = new RestRequest(Method.GET); request.AddHeader("Authorization", "Bearer "); IRestResponse response = client.Execute(request); ```