Official OxiSMS Python Library

Overview
This repository contains the official Python library for the OxiSMS API.
You don't have to know how the API works to use it: every route is available through typed Python objects,
documented with docstrings.
To get started, create an account on account.oxemis.com (a free trial is available).
What is OxiSMS?
OxiSMS is a solution designed to let you send your SMS quickly and easily, from our web application,
our software, or your own programs with this library.
We offer worldwide coverage and sender personalization when it is allowed by the operators of your recipients
(see the destinations).
All our SMS are sent via Premium routes, for the best possible deliverability.
We're a small team, but we're recognized for the quality of our support and expertise.
Table of contents
- Requirements
- Installation
- Quick start
- Authentication and client options
- Getting information about your account
- Sending SMS
- Your first SMS
- Customized messages
- Using a custom sender
- How many characters can I put in my message?
- How many credits will a sending use?
- Choosing the strategy
- Scheduling a sending
- Letting your recipients reply
- Shortening a URL
- Tracking your messages
- Status of a sending
- Status over a period (pagination)
- Replies
- Statistics
- History of your sendings
- Unsubscribe list and bounce list
- Phone number analysis
- Error handling
- Dates and time zones
- Testing your code without calling the API
- Links
- Contribute
Requirements
- Python 3.10 or higher;
- httpx 0.24 or higher (installed with the library, its only dependency).
Installation
pip install oxisms
Quick start
import os
from oxisms import Message, OxiSmsClient
client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
message = Message(text="Hi there! This is my first SMS sent with the oxisms Python library.")
message.add_recipient("+33600000001")
sending = client.send_api.send(message)
print(f"Sending ID: {sending.sending_id}, cost: {sending.total_cost} credit(s)")
Authentication and client options
You can create your API keys in your Oxemis account.
We recommend keeping them out of your code, in environment variables:
export OXISMS_API_LOGIN='your API login'
export OXISMS_API_PWD='your API password'
import os
from oxisms import OxiSmsClient
client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
# Optional settings (keyword arguments), all optional:
client = OxiSmsClient(
os.environ["OXISMS_API_LOGIN"],
os.environ["OXISMS_API_PWD"],
timeout=30, # maximum duration of a request, in seconds (default 30)
connect_timeout=10, # maximum duration to connect, in seconds (default 10)
max_retries=3, # retries on "429 Too Many Requests", honoring Retry-After (default 3, 0 to disable)
user_agent="MyApp/2.0", # added at the end of the User-Agent header: "oxisms-python/1.0.0 (Python 3.13.1) MyApp/2.0"
# base_url="https://api.oxisms.com", # URL of the API
# transport=..., # an httpx transport, for your tests (see below)
# http_client=httpx.Client(...), # your own httpx client (proxies, certificates...)
)
With http_client, the settings of your client apply (timeout, connect_timeout and transport are then
ignored) and the library does not close it.
The client keeps its connections open between calls. Use it as a context manager (or call client.close())
to close them when you are done:
with OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"]) as client:
print(client.user_api.get_user().credits)
The client gives access to every feature of the API through these attributes:
| Attribute |
What for |
user_api |
your account: company name, credits, rates |
send_api |
send SMS now or later, compute their cost, list and cancel scheduled sendings |
senders_api |
your custom senders |
tracking_api |
delivery status, replies of your recipients, statistics |
history_api |
the sendings made on your account |
blacklists_api |
your unsubscribe list (historical name of the route) |
bounces_api |
your bounce list (invalid numbers) |
tools_api |
phone number analysis, URL shortener, health check of the API |
Every object returned by the library is a frozen dataclass with typed attributes (the package ships its
type hints: mypy --strict and your IDE know every field).
Getting information about your account
import os
from oxisms import OxiSmsClient
client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
user = client.user_api.get_user()
print(f"Name: {user.company_name}")
print(f"Remaining credits: {user.credits}")
# Last day of validity of your credits, INCLUDED (None if they don't expire)
if user.credits_valid_before is not None:
print(f"Valid until: {user.credits_valid_before:%Y-%m-%d} (included)")
if not user.is_credits_valid_on():
print("Your credits have expired.")
# Rates: cost in credits of one SMS, per destination
for rate in user.rates:
print(f"{rate.country} (+{rate.country_code}): {rate.cost} credit(s)")
print(f"France: {user.get_rate_for_country_code(33)} credit(s) per SMS")
credits is a float: some destinations cost more than one credit per SMS (1.7 for example), so your balance
may have decimals.
Sending SMS
Your first SMS
Build a Message, then send it with client.send_api.send():
import os
from oxisms import Message, OxiSmsClient
client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
message = Message(
text="Hi there! This is my first SMS sent with the oxisms Python library.",
campaign_name="Welcome", # optional, groups your sendings in your history and statistics
)
message.add_recipient("+33600000001").add_recipient("+33600000002")
sending = client.send_api.send(message)
print(f"Sending ID: {sending.sending_id}") # to follow it with tracking_api
print(f"Cost: {sending.total_cost} credit(s)")
for recipient in sending.ok_recipients:
print(f"{recipient.msisdn}: message {recipient.token}")
for recipient in sending.filtered_recipients:
# FILTERED_UNSUBSCRIBED, FILTERED_BOUNCED or FILTERED_NOT_COVERED
print(f"{recipient.phone_number} was removed: {recipient.filtered_reason}")
for recipient in sending.invalid_recipients:
print(f"{recipient.phone_number} is not a valid number")
Phone numbers should be given in international format (+33600000001 or 33600000001); French national
numbers (0600000001) are also accepted. If no valid recipient is left, nothing is sent and sending_id is
None.
Customized messages
Every {{Name}} in the text is replaced by the meta data Name of each recipient:
import os
from oxisms import Message, OxiSmsClient, Recipient
client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
message = Message(
text="Hi {{Name}}! This is your ID: {{ID}}",
recipients=[
Recipient("+33600000001", {"Name": "Joe", "ID": 1}),
Recipient("+33600000002", {"Name": "Jane", "ID": 2}),
],
)
# Same thing, one by one: message.add_recipient("+33600000003", {"Name": "Ann", "ID": 3})
# Two messages in one call: "Hi Joe! This is your ID: 1" and "Hi Jane! This is your ID: 2"
client.send_api.send(message)
If a merge field is missing for some recipients, the sending is refused with an OxiSmsError whose reason
is UNKNOWN_MERGE_FIELDS (see Error handling).
Using a custom sender
By default, SMS are sent with a short code (36xxx in France for example). You can display your own sender
instead:
- an alphanumeric sender: 3 to 11 characters (letters A-Z, digits, spaces), with at least one letter.
It must first be added to your senders and validated by our team;
- a numeric sender: 3 to 15 digits.
Some operators don't accept custom senders: a short code is then used. With the commercial strategy,
an unsubscribe mention is added to your message ("STOP au 36111" for example), which makes it longer.
import os
from oxisms import Message, OxiSmsClient
client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
# 1. Add the sender (once): it stays pending until our team validates it
result = client.senders_api.add_sender("MyShop")
if not result.is_success:
print(result.errors) # e.g. {"My Shop": "Invalid sender: must be alphanumeric, no spaces, ..."}
# 2. Check its status
senders = client.senders_api.get_senders()
print(senders.validated) # usable senders
print(senders.pending) # waiting for validation
print(senders.blocked) # refused (contact the support to know why)
# 3. Use it
if senders.is_validated("MyShop"):
message = Message(text="Your order is ready!", sender="MyShop").add_recipient("+33600000001")
client.send_api.send(message)
# Remove a sender (the result tells whether it was refused, like add_sender())
client.senders_api.delete_sender("OldName")
How many characters can I put in my message?
It depends on the encoding (see What is encoding?):
- GSM (letters, digits, common punctuation and some accents): up to 160 characters per SMS;
- Unicode (emojis, other accents such as
ê...): up to 70 characters per SMS;
- longer messages are sent as a long SMS of up to 8 parts, displayed as one message on the phone;
each part then holds 153 characters (GSM) or 67 characters (Unicode), and costs one SMS.
Keep the default ENCODING_AUTO: OxiSMS uses GSM when the text allows it, Unicode otherwise.
You can force it with encoding=ENCODING_GSM (characters outside the GSM alphabet are replaced, ê becomes
e) or encoding=ENCODING_UNICODE.
More details in the FAQ.
from oxisms import ENCODING_UNICODE, Message
message = Message(text="Merry Christmas 🎄", encoding=ENCODING_UNICODE) # or Message.ENCODING_UNICODE
How many credits will a sending use?
Use get_cost_of_message(): nothing is sent and no credit is used.
import os
from oxisms import Message, OxiSmsClient
client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
message = Message(text="Our sales start tomorrow!")
message.add_recipient("+33600000001").add_recipient("+32470000001")
cost = client.send_api.get_cost_of_message(message)
print(f"This sending will use {cost.total_cost} credit(s), you have {cost.credits}")
if cost.insufficient_credits:
print("Not enough credits: the sending would be refused.")
for recipient in cost.ok_recipients:
print(f"{recipient.msisdn}: {recipient.cost} credit(s), {recipient.encoding}")
You can also set a maximum with max_credits_per_sending: if the sending would cost more, it is refused.
from oxisms import OxiSmsError
message.max_credits_per_sending = 1
try:
client.send_api.send(message)
except OxiSmsError as e:
# Code 406: "Total credits needed to send the message (2) exceeds the MaxCreditsPerSending parameter (1)."
print(f"{e.code}: {e.message}")
Choosing the strategy
| Strategy |
Use it for |
Restrictions |
| Commercial (default) |
marketing messages, i.e. anything that promotes your activities or events, even free ones |
Not sent after 9:00 p.m., before 8:00 a.m., on Sundays and public holidays. They are not rejected: they are automatically postponed to the next allowed period. |
| Notification |
notifications (password reset, two-factor code, appointment reminder...) |
None |
Please be very careful selecting the strategy. Sending marketing messages with the "notification" strategy
will probably get your account locked because of complaints from your recipients.
See What strategy should I choose?
import os
import secrets
from oxisms import STRATEGY_NOTIFICATION, Message, OxiSmsClient
client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
two_factor_code = 100000 + secrets.randbelow(900000)
message = Message(text=f"Here is your code to authenticate: {two_factor_code}", strategy=STRATEGY_NOTIFICATION)
message.add_recipient("+33600000001")
client.send_api.send(message)
Scheduling a sending
The date must be at least 5 minutes away and no more than 90 days away. The credits are used when the sending
is scheduled and given back if you cancel it.
import os
from datetime import datetime, timedelta
from oxisms import Message, OxiSmsClient
client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
tomorrow_evening = (datetime.now().astimezone() + timedelta(days=1)).replace(hour=18, minute=0, second=0)
message = Message(
text="Reminder: your appointment is tomorrow at 10:00.",
scheduled_datetime=tomorrow_evening,
).add_recipient("+33600000001")
sending = client.send_api.send(message)
# List the scheduled sendings (empty list if there is none)
for scheduled in client.send_api.get_scheduled():
print(f"{scheduled.sending_id} on {scheduled.scheduled_datetime}: "
f"{scheduled.nb_sms} SMS, {scheduled.cost} credit(s)")
# Cancel one (raises an OxiSmsError, code 404, if it is unknown or no longer scheduled)
client.send_api.delete_scheduled(sending.sending_id)
Letting your recipients reply
With the reply mode, your recipients can answer your SMS (a custom sender can't be used with it).
See How does the response mode work?
import os
from oxisms import Message, OxiSmsClient
client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
message = Message(text="Will you attend our meeting on Friday? Answer YES or NO.", allow_reply=True)
message.add_recipient("+33600000001")
sending = client.send_api.send(message)
# Later: read the replies (see "Replies" below)
for reply in client.tracking_api.get_replies_for_sending(sending.sending_id):
print(f"{reply.from_} answered: {reply.message}")
Shortening a URL
Short URLs save characters, and some URLs refused by the operators (other URL shorteners for example) are made
safe: