How to Send an SMS from a Python Script
To send an SMS from Python, POST to and body to https://smsnet.net/api/v1/messages/send with your key in the X-API-Key header. The call returns a message_id and your quota, and the text leaves from your own Android number. Ten lines with requests, or the standard library alone.
What do I need before the first call?
Two things: a connected phone and an API key. Install the SMSNET Gateway app on any Android 8.0 or newer phone with a SIM, sign in, and the last screen of setup shows your key once. The Android gateway guide shows every screen. Put the key in an environment variable rather than in the script; it can be rotated from the Developers page if it ever leaks.
The free plan is enough to build against: 300 messages a month, 20 a day, and replies are never counted. Recipients go in E.164 format (+15551234567), and the person you are texting should have agreed to hear from you.
How do I send an SMS with the requests library?
import os
import requests
API = "https://smsnet.net/api/v1"
HEADERS = {"X-API-Key": os.environ["SMSNET_API_KEY"]}
def send_sms(to: str, body: str, transactional: bool = False) -> dict:
r = requests.post(
f"{API}/messages/send",
headers=HEADERS,
json={"to": to, "body": body, "transactional": transactional},
timeout=15,
)
if r.status_code == 429:
# Plan allowance reached; the text explains which limit and how far over.
raise RuntimeError(r.json().get("error"))
r.raise_for_status()
return r.json()
result = send_sms("+15551234567", "Your table is ready. Reply STOP to opt out.")
print(result["message_id"], result["quota"]["day"])
A successful response looks like this:
{
"ok": true,
"message_id": "msg_01j9x8k2...",
"conversation_id": "conv_01j9x8k2...",
"device_id": "dev_01j9x8k2...",
"quota": {
"month": { "used": 13, "limit": 300 },
"day": { "used": 4, "limit": 20 }
}
}
quota is there so a script can slow down before it hits the wall instead of discovering it as a 429. The limit has a fifth of headroom above it; once you are in that band the response carries "grace": true and a note.
Set transactional=True only for a message the recipient is waiting on right now, such as a login code. It skips the queue's pacing gap and quiet hours and reaches the phone in about a second, while still respecting the daily ceiling and the warmup ramp on a new line. Marking a promotion transactional to make it go faster is the quickest way to get a number flagged, and it is the one thing the flag is not for.
Can I send an SMS from Python without any dependencies?
Yes. The standard library version is the same request:
import json
import os
import urllib.request
req = urllib.request.Request(
"https://smsnet.net/api/v1/messages/send",
data=json.dumps({"to": "+15551234567", "body": "Build 412 passed on main."}).encode(),
headers={"X-API-Key": os.environ["SMSNET_API_KEY"], "Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=15) as resp:
print(json.load(resp)["message_id"])
That is the whole integration for a deploy notifier, a cron job that texts you when a disk fills, or a test that needs a real SMS to arrive on a real handset.
What happens to the message after the POST returns?
The POST queues the message; it does not wait for the phone. The message moves through a small set of states, and you can watch them either by polling or by webhook.
Every state a message can be in, and where you can observe it.
| Status | Meaning | Typical time |
|---|---|---|
pending | Queued, waiting for a line with capacity | Seconds to minutes; a transactional message skips this wait |
ready | Handed to a specific SIM, the phone will send on its next fetch | About a second with the current app |
sent | The carrier accepted the message from the phone | Seconds after ready |
delivered | The recipient's handset confirmed receipt | Seconds to minutes, carrier dependent |
failed | The phone could not send it after repeated attempts | Reported with an error_message |
expired | No line picked it up before expires_at | Default 24 hours; set expires_in_hours from 1 to 336 |
How do I read replies in Python?
Two options. Polling needs no public URL and suits a script; a webhook suits a server.
Polling uses the message feed with a cursor. The first call without since returns the latest messages; every call after that passes back next_cursor, so nothing is missed or repeated even when several messages share a millisecond.
import time
cursor = None
while True:
params = {"direction": "inbound", "limit": 100}
if cursor:
params["since"] = cursor
page = requests.get(f"{API}/messages", headers=HEADERS, params=params, timeout=15).json()
for m in page["messages"]:
print(m["from_number"], m["body"], m["conversation_id"])
cursor = page["next_cursor"] or cursor
if not page["has_more"]:
time.sleep(10)
For a webhook, register your HTTPS endpoint once (PUT /api/v1/webhooks with {"url": "..."}) and keep the secret from the response. SMSNET then POSTs message.received and message.status events, signs each one, and retries nine times over about three days if your endpoint is down. Verify the signature before trusting anything:
import hmac, hashlib, time
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = os.environ["SMSNET_WEBHOOK_SECRET"]
@app.post("/sms")
def sms_webhook():
ts = request.headers.get("X-SMSNET-Timestamp", "")
sig = request.headers.get("X-SMSNET-Signature", "")
if abs(time.time() - int(ts or 0)) > 300:
abort(400) # older than the 5 minute tolerance, or missing
expected = "v1=" + hmac.new(SECRET.encode(), f"{ts}.".encode() + request.get_data(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, sig):
abort(400)
event = request.get_json()
if event["event"] == "message.received":
print("reply from", event["data"]["from"], ":", event["data"]["body"])
elif event["event"] == "message.status":
print(event["data"]["message_id"], "is now", event["data"]["status"])
return "", 200
The signed material is the timestamp, a dot, and the raw request body, so verify against request.get_data() before anything parses it. Dedupe on the X-SMSNET-Delivery header, which is stable across retries. Send yourself a test event with POST /api/v1/webhooks/test before any real traffic exists.
What errors should the script expect?
| Status | When | What to do |
|---|---|---|
| 400 | Missing to or body, or no phone connected to the account | Fix the request, or connect a phone |
| 401 | Missing or wrong key; the error says whether the key was rotated | Load the key from the environment, rotate if needed |
| 403 | The recipient opted out; the error names the date and the words they used | Do not retry; remove them from your list |
| 429 | Monthly or daily allowance reached, including the headroom | Wait for the window, or upgrade the plan |
Everything in this guide runs on the free plan. For the full endpoint list, including conversations, contacts and campaigns, see What Is an SMS API and How to Use One. If you would rather have an AI agent do the calling, the MCP server guide exposes the same operations as tools.
FAQ
How do I send an SMS from a Python script?
POST JSON with to and body to https://smsnet.net/api/v1/messages/send, with your SMSNET API key in the X-API-Key header. The response returns a message_id and your remaining quota, and the message is sent from the Android phone connected to your account. The requests version is about ten lines; the standard library version needs nothing installed.
Do I need Twilio or a carrier account to send SMS from Python?
No. SMSNET uses an Android phone and SIM you already own as the sender, so there is no carrier account and no number rental; you text from your own number on your own plan. The free plan covers 300 messages a month and replies are never counted.
How do I know the SMS was delivered?
Either poll GET /api/v1/messages and read each message's status, or register a webhook and receive a message.status event when the message reaches sent, delivered or failed. Delivery confirmation comes from the recipient's handset via the carrier, so timing varies by network.
Can my Python script receive SMS replies?
Yes. Poll GET /api/v1/messages?direction=inbound with the next_cursor from the previous call, or register an HTTPS webhook and receive message.received events signed with HMAC-SHA256 over the timestamp and raw body.
How fast does the message arrive?
An ordinary message is paced and usually leaves within a minute or two, subject to civil hours where the recipient is. A message marked transactional is handed to the phone immediately and typically reaches the handset in about a second. New lines are limited to 100 messages a day until they have warmed up.
What phone number does the recipient see?
The number of the SIM in your connected Android phone. It is your own number, so replies come straight back to you and the conversation stays in one thread.
Related guides
This is a spoke of What Is an SMS API and How to Use One. Siblings: Send an SMS from Node.js and Send an SMS with cURL. The phone comes from Turn Your Android Phone into an SMS Gateway; the agent route is What Is an MCP Server for SMS?.
Send your first message today
Free plan, no card: 400 messages a month from your own number, with the API, webhooks and MCP included.
Get the app See pricing