Connecting AI Agents to SMS and Email APIs: A Developer Guide
Tutorials

Connecting AI Agents to SMS and Email APIs: A Developer Guide

Ping TeamFebruary 8, 202611 min read

AI agents are increasingly being deployed as autonomous workers that handle tasks end-to-end. A common requirement is the ability to communicate with external parties via SMS and email: sending appointment confirmations, alerting users about anomalies, dispatching reports, or following up on leads. This guide covers the technical details of connecting your AI agent to Ping SMS and email APIs.

Authentication and API Keys

Every AI agent that sends messages through Ping needs an API key. Use the secret key (sk_live_*) for server-side agents and the public key (pk_live_*) for less sensitive operations. Create a dedicated API key for each agent or agent type, with permissions scoped to only the channels the agent needs. This limits blast radius if a key is compromised.

python
import os
import requests

class PingMessagingClient:
    """Thin wrapper around Ping API for AI agent use."""

    def __init__(self):
        self.api_key = os.environ["PING_API_KEY"]
        self.base_url = "https://api.ping.co.zw/api"
        self.headers = {
            "x-api-key": self.api_key,
            "Content-Type": "application/json",
        }

    def send_sms(self, to: str, message: str, sender_id: str = None) -> dict:
        payload = {"to": to, "message": message}
        if sender_id:
            payload["senderId"] = sender_id
        resp = requests.post(
            f"{self.base_url}/sms/send",
            headers=self.headers,
            json=payload,
            timeout=10,
        )
        resp.raise_for_status()
        return resp.json()

    def send_email(self, to: str, subject: str, html_body: str, from_addr: str) -> dict:
        resp = requests.post(
            f"{self.base_url}/email/send",
            headers=self.headers,
            json={
                "to": to,
                "subject": subject,
                "htmlBody": html_body,
                "from": from_addr,
            },
            timeout=10,
        )
        resp.raise_for_status()
        return resp.json()

Error Handling and Retries

AI agents must handle API failures gracefully. Ping returns standard HTTP status codes: 200 for success, 400 for bad requests, 401 for authentication failures, 429 for rate limits, and 500 for server errors. Implement exponential backoff for retries on 429 and 500 errors. Never retry 400 or 401 errors, as those indicate a problem with your request or credentials.

python
import time

def send_with_retry(client, channel, **kwargs):
    max_retries = 3
    for attempt in range(max_retries):
        try:
            if channel == "sms":
                return client.send_sms(**kwargs)
            elif channel == "email":
                return client.send_email(**kwargs)
        except requests.exceptions.HTTPError as e:
            if e.response.status_code in (429, 500, 502, 503):
                wait = 2 ** attempt  # 1s, 2s, 4s
                time.sleep(wait)
                continue
            raise  # Don't retry 400/401
    raise Exception(f"Failed after {max_retries} retries")

Multi-Channel Orchestration

A sophisticated AI agent can choose the optimal channel based on the message type and recipient preferences. Urgent alerts go via SMS (highest immediacy). Detailed reports go via email (supports rich formatting and attachments). Conversational interactions go via WhatsApp (supports two-way dialogue). The agent should maintain a preference model per recipient and fall back to alternative channels on failure.

Store recipient channel preferences and delivery history. If SMS consistently fails for a recipient (possibly a landline or deactivated number), the agent should automatically switch to email or WhatsApp.

Rate Limiting Considerations

Ping applies rate limits to prevent abuse. If your AI agent sends high volumes, implement a message queue (Redis, RabbitMQ, or a simple in-memory queue) to buffer outgoing messages and respect rate limits. Batch operations where possible using the bulk SMS endpoint for large recipient lists.

Get API Key

Get Started