Send SMS with Python from your own phone.
To send an SMS from Python, POST a number and a message to https://app.sms8.io/api/v1/messages with your API key in the X-Api-Key header. The requests library is all you need. The text leaves from the SIM in your own Android phone, with no per-message fee and no A2P 10DLC filing.
Quick start in three steps
From a new account to a delivered text in a few minutes.
Get your API key
Create an SMS8 account, pair an Android phone with the SMS8 app, and copy your key from the API page of the dashboard. Store it in an environment variable called SMS8_API_KEY.
Install requests
Run pip install requests. There is no SDK to install for Python. The API takes a normal form post and answers in JSON.
Send your first SMS
Run the snippet below with your own number. The phone you paired sends the text from its SIM, and you get a message ID back.
How do I send an SMS with Python?
One request with two fields: number in international format and message. Your key goes in the X-Api-Key header.
import os
import requests
API = "https://app.sms8.io/api/v1"
HEADERS = {"X-Api-Key": os.environ["SMS8_API_KEY"]}
r = requests.post(f"{API}/messages", headers=HEADERS, data={
"number": "+14155550100",
"message": "Hello from Python and SMS8",
}, timeout=30)
body = r.json()
if body.get("success"):
print("queued as", body["data"]["messages"][0]["ID"])
else:
print("refused:", body["error"]["code"], body["error"]["message"])
Every answer has the same shape: a success flag, a data object and an error object with a code and a message. Always read the flag, because some refusals, such as no credits left, come back inside a normal response.
How do I send SMS to many numbers in Python?
For the same text to several people, pass the numbers comma-separated in number. Add option=1 to rotate across every phone you paired, or option=2 to rotate across every SIM, including both slots of a dual-SIM phone.
numbers = ["+14155550100", "+14155550101", "+14155550102"]
r = requests.post(f"{API}/messages", headers=HEADERS, data={
"number": ",".join(numbers),
"message": "The store opens at 9:00 tomorrow.",
"option": 1,
}, timeout=30)
ids = [m["ID"] for m in r.json()["data"]["messages"]]
For a different text per person, send a messages field holding a JSON list of objects, each with its own number and message:
import json
batch = [
{"number": "+14155550100", "message": "Hi Ana, your table for 4 is ready."},
{"number": "+14155550101", "message": "Hi Ben, your order #4412 has shipped."},
]
r = requests.post(f"{API}/messages", headers=HEADERS, data={
"messages": json.dumps(batch),
}, timeout=30)
To send later, add schedule with a Unix timestamp, for example int(time.time()) + 3600 for one hour from now. For codes and alerts that must go first, add prioritize=1 so the message jumps ahead of a running batch.
Pacing matters for bulk sends. The API has no artificial rate limit, but each SIM should send about one message every 10 to 30 seconds. To send more, add phones and use rotation.
How do I send an MMS with Python?
Set type to mms and put public image links in attachments, separated by commas. JPG, PNG, GIF and WEBP work, and SMS8 resizes each image to 1,280 pixels before sending.
r = requests.post(f"{API}/messages", headers=HEADERS, data={
"number": "+14155550100",
"message": "Here is your receipt and the map to our store.",
"type": "mms",
"attachments": "https://example.com/receipt.jpg,https://example.com/map.png",
}, timeout=30)
The links must be reachable from the internet, not from localhost. More detail on picture messages in the guide on sending MMS through an API.
How do I read SMS replies in Python?
Two ways. Webhooks push each reply to your server the moment it reaches your phone, which is what a live app needs. Polling the read endpoint is fine for a script or a nightly report.
Poll for messages received in the last hour
import time
r = requests.post(f"{API}/messages/read", headers=HEADERS, data={
"status": "Received",
"startTimestamp": int(time.time()) - 3600,
"limit": 100,
}, timeout=30)
body = r.json()
inbox = body["data"]["messages"] if body.get("success") else []
for m in inbox:
print(m["number"], m["message"])
When nothing matches, the answer is success: false with error code 404. Treat that as an empty list. You can also filter by id, deviceID, simSlot or endTimestamp, and page with limit and offset.
Receive replies with a signed webhook (Flask)
Add an HTTPS URL on the Webhooks page of your dashboard and subscribe it to received messages. SMS8 posts JSON to it, with an X-Signature header: sha256= followed by the hex HMAC-SHA256 of the raw body, keyed with that webhook's own signing secret (not your API key).
import hashlib
import hmac
import os
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.environ["SMS8_WEBHOOK_SECRET"].encode()
@app.post("/sms8/webhook")
def sms8_webhook():
raw = request.get_data()
expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, request.headers.get("X-Signature", "")):
abort(401)
event = request.get_json()
for m in event.get("data", []):
save_reply(m["ID"], m["number"], m["message"]) # your code: dedupe on ID
return "", 200
A received message arrives with event, timestamp, userID and a data list where each item has ID, number, message, deviceID and simSlot. Answer with a 2xx within 10 seconds and do slow work after. If your server is down, SMS8 retries on a growing schedule for up to 30 days, so store the message ID with a unique index and skip repeats.
Not sure which approach fits? Read webhook vs polling for incoming SMS.
Errors and retries
| What you see | Meaning | What to do |
|---|---|---|
| Error code 401 | Missing or wrong API key | Fix the key. Do not retry |
| Error code 400 | Missing or malformed fields | Fix the request. Do not retry |
success: false with a message | Refused, for example no credits left | Log and alert. Retrying will not help |
| Error code 404 on a read | No messages match | Treat as an empty list |
| Error code 500, HTTP 5xx or a timeout | Temporary problem | Retry with backoff |
Retry only on timeouts and server errors. Pass an idempotencyKey, such as your order ID plus the message type, so a retry never becomes a second text. SMS8 also returns the first answer for an identical request repeated within five minutes.
import time
class Permanent(Exception):
pass
def send_with_retry(number, text, key, attempts=4):
for i in range(attempts):
try:
r = requests.post(f"{API}/messages", headers=HEADERS, data={
"number": number, "message": text, "idempotencyKey": key,
}, timeout=30)
body = r.json()
if body.get("success"):
return body["data"]["messages"][0]
if r.status_code < 500 and body["error"]["code"] != 500:
raise Permanent(body["error"]["message"]) # 400, 401, no credits
except (requests.Timeout, requests.ConnectionError):
pass
time.sleep(2 ** i) # 1s, 2s, 4s, 8s
raise RuntimeError("SMS8 send failed after retries")
send_with_retry("+14155550100", "Your order #4412 has shipped.", "order-4412-shipped")
If the phone later reports a message as failed, for example because it had no signal, do not send a new copy. Put the original back in the queue by its ID, and always pass the id:
requests.post(f"{API}/messages/resend", headers=HEADERS, data={"id": 128476}, timeout=30)
The full list of endpoints and fields is in the SMS8 API documentation, and the longer walkthrough with Node, PHP and curl side by side is the SMS API guide for developers.
Why choose SMS8 for Python
An SMS API without a number to rent or a meter to watch.
Your own number
Texts leave from the SIM in your own Android phone, so customers see a number they know and can reply to it.
Flat price, unlimited messages
USD 29 a month for one phone, USD 89 for five and USD 229 for twenty, with unlimited SMS and MMS and no per-message fee. Yearly billing is half the price.
No A2P 10DLC filing
Texts go person-to-person from your SIM, so there is no brand or campaign registration to wait for.
Plain HTTP, no SDK lock-in
A form post with requests is the whole integration. The same code runs in Django, FastAPI, Flask, a Celery worker or a cron script.
Signed webhooks with long retries
Replies arrive at your server signed with HMAC-SHA256 and are retried for up to 30 days if your server is down.
Setup in minutes, with a trial
Pair a phone, copy a key and send. The 3-day trial includes 30 messages and needs no card.
Keep going
The reference, the guides and the same examples in other languages.
SMS8 API documentation
Every endpoint, field and webhook event in one place.
Open the docsSMS API guide for developers
Sending, receiving, signatures, retries and pacing, with code in four languages.
Read the guideWebhook vs polling
Which way to receive incoming SMS, and a clean polling loop when you need one.
Read the articleSend SMS with Node.js
The sms8-sdk package from npm, plus plain fetch.
Node.js examplesSend SMS with PHP
curl, hash_hmac and a ready PHP class.
PHP examplesSend SMS with C#
HttpClient and an ASP.NET Core webhook.
C# examplesSend SMS with curl
Test every endpoint from the terminal.
curl examplesYou do not need one. The API takes a form post and answers in JSON, so the requests library is enough. The dashboard API page has a request builder that shows each call ready to copy in Python.
Start the SMS8 trial: 3 days and 30 messages with no card. After that, a flat plan from USD 29 a month covers unlimited SMS and MMS from your own phone, with no fee per message.
Yes. With SMS8 your Python code posts to app.sms8.io and the text goes out from the SIM in your own Android phone. There is no number to rent and no per-message fee from SMS8.
The API has no artificial limit. Each SIM should send about one message every 10 to 30 seconds, so add phones and set option to 1 or 2 to rotate across them when you need more volume.
Compute sha256= plus the hex HMAC-SHA256 of the raw request body with your webhook signing secret, and compare it to the X-Signature header with hmac.compare_digest.
Send your first SMS from Python
Pair a phone, copy your API key and run the snippet. 3-day trial with 30 messages, no card needed.