SDK

Python SDK

A Python SDK with no third-party dependencies: SMS, contacts, lists, sender IDs and SMTP email.

Runtime

Python 3.9+

Package

messageglobe

PyPI · coming soon

Dependencies

None: the SDK builds only on urllib, smtplib and email from the standard library.

Licence

MIT

Open source on GitHub

The SDK has no framework dependencies and drops cleanly into Django, Flask, FastAPI, Celery workers or a plain script. A single API token — the one from the developers dashboard — authorises every REST feature: SMS, contacts, lists and sender IDs. Email is configured separately over SMTP.

Features

Five modules, one integration

SMS

REST API v3

send, delivery status

Contact management

REST API v3

create, delete

Lists (groups)

REST API v3

create, show, update, delete, list

Sender ID

REST API v3

list, show, create, delete

Email

SMTP

send (HTML + text, attachments)

Installation

Add the SDK to your project

Shell
pip install messageglobe

The package is not published on PyPI yet: install it straight from GitHub.

Shell
pip install git+https://github.com/Message-Globe/messageglobe-python.git

Quick start

From token to first send

Use the unified facade, or each client on its own. Copy the token from the developers dashboard — it covers every REST feature.

Python
from messageglobe import ContactRequest, EmailMessage, MessageGlobe, SmsMessage mg = MessageGlobe.create(    # Copy your token from the developers dashboard.    # This one token powers all REST features.    api_token="XX|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",    smtp={        "host": "smtp.messageglobe.com",        "port": 587,        "from_address": "no-reply@yourapp.com",        "from_name": "YourApp",        "username": "smtp-user",        "password": "smtp-password",        "encryption": "tls",    },) # Send an SMSresponse = mg.sms.send(    SmsMessage(to="393612345678", sender_id="YourName", message="This is a test message"))print(response.message_id) # Create a contactcontact = mg.contacts.create("list_uid_example", ContactRequest(phone="393310000000"))print(contact.uid) # Send an emailmg.email.send(    EmailMessage(        to="jane@example.com",        subject="Welcome",        html="<h1>Hi Jane</h1>",        text="Hi Jane",    ))
Get your API token

SMS

Sending, gateways and delivery reports

The same configuration is shared by every REST client. You can set the language of the API responses to Italian or English.

Python
from messageglobe import ApiConfig, SmsClient client = SmsClient(ApiConfig("XX|your-api-token")) # Language of the API responses: "en" or "it".client = SmsClient(ApiConfig("XX|your-api-token", accept_language=ApiConfig.LANGUAGE_IT))

Gateway HQ high_quality()

Custom sender ID and delivery reports. The sender field is required.

Gateway LQ low_quality()

No custom sender and no delivery report.

Sending a message
from messageglobe import SmsMessage response = client.send(    SmsMessage(        to="393612345678",          # a single number, "n1,n2" or a list        sender_id="YourName",       # max 11 chars if alphanumeric        message="Hello world",        dlr_callback_url="https://yourapp.com/webhooks/dlr",  # optional, HQ only    )) result = response.first()print(result.message_id)   # "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"print(result.status)       # "Sent"print(result.cost)         # 0.06

The message type (plain or unicode) defaults to plain. Let the SDK pick it from the content: messages with non-GSM characters (emoji, Cyrillic, …) are sent as unicode.

Automatic type
SmsMessage(to="393612345678", sender_id="YourName", message="Привет 😀", auto_type=True)# sms_type becomes "unicode" automatically # The mutators chain, also after construction:message = SmsMessage().to("393612345678").set_message("Hello world").low_quality()
Multiple recipients
response = client.send(    SmsMessage(        to=["393612345678", "880172145789"],  # or "393612345678,880172145789"        sender_id="YourName",        message="Hello everyone",    )) for result in response:    print(result.recipient, "=>", result.message_id)
Checking the status
result = client.status("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") print(result.status)       # e.g. "Delivered"print(result.updated_at)

With the HQ gateway and a DLR callback, MessageGlobe POSTs a JSON payload to your endpoint on every delivery update.

DLR webhook payload
{    "message_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",    "recipient": "393612345678",    "sender_id": "YourName",    "status_code": 1,    "status": "Delivered",    "updated_at": "2024-06-28T11:41:51.000000Z"}

status_code values: 1 Delivered, 2 Failed, 8 Sent.

Explore the Messaging API

Contact management

Contact records inside your lists

Contacts live inside a list identified by its group id. Use the same API token as SMS.

Python
from messageglobe import ApiConfig, ContactRequest, ContactsClient client = ContactsClient(ApiConfig("XX|your-api-token")) # At least one of phone or email is required.contact = client.create(    "list_uid_example",    ContactRequest(phone="393310000000", first_name="Jane", last_name="Doe"),) print(contact.uid)          # "contact_uid_example"print(contact.status)       # "subscribe" # Delete by passing the list and the contact uid.client.delete("list_uid_example", "contact_uid_example")

Lists (groups)

The container for your contacts

A list — or group — is the container contacts belong to: its uid is the group id used by the Contacts client.

Python
from messageglobe import ApiConfig, GroupsClient client = GroupsClient(ApiConfig("XX|your-api-token")) group = client.create("Newsletter subscribers")uid = group.uid group = client.show(uid)group = client.update(uid, "VIP subscribers") client.delete(uid) # List all the lists (raw, paginated data)page = client.all()

Sender ID

Manage the senders on your account

Sender IDs are the custom senders used with the HQ gateway. You can list them, look them up, request new ones and delete them via the API.

Python
from messageglobe import ApiConfig, SenderIdRequest, SendersClient client = SendersClient(ApiConfig("XX|your-api-token")) # List all sender IDsfor sender in client.all():    print(sender.sender_id, "=>", sender.status)  # "active" / "pending" # Look up a sender ID by namesender = client.show("YourName") # Create a new one: all fields are required, 3-11 chars.sender = client.create(    SenderIdRequest(        sender_id="YourName",        company="Your Company",        tax_code="ABCDEF12G34H567I",        vat_code="01234567890",        address="Via Roma 1",        city="Rome",        province="RM",        country="IT",        email_address="you@example.com",        phone="391234567890",        pec_address="you@pec.example.com",    )) # Delete by nameclient.delete("YourName")

In Italy alphanumeric aliases follow the AGCOM code of conduct: new sender IDs are submitted for approval.

Read the AGCOM code of conduct

Email

Transactional email over SMTP

Send HTML and text email with attachments, CC, BCC and reply-to. Encryption options are TLS (STARTTLS), SSL (SMTPS) or none.

Python
from messageglobe import Attachment, EmailClient, EmailMessage, SmtpConfig client = EmailClient(    SmtpConfig(        host="smtp.messageglobe.com",        port=587,        from_address="no-reply@yourapp.com",        from_name="YourApp",        username="smtp-user",        password="smtp-password",        encryption=SmtpConfig.ENCRYPTION_TLS,    )) message = (    EmailMessage(subject="Your report")    .to("jane@example.com", "Jane Doe")    .cc("team@example.com")    .reply_to("support@yourapp.com")    .html("<h1>Report ready</h1><p>See attachment.</p>")    .text("Report ready. See attachment.")    .attach(Attachment.from_path("/path/to/report.pdf"))    .attach(Attachment.from_content(csv_string, "data.csv", "text/csv"))) client.send(message)

MessageGlobe provides SMTP on dashboard.messageglobe.com:465 (SSL): your username is your login and your password is the API token. There is a dedicated preset.

MessageGlobe SMTP preset
config = SmtpConfig.for_messageglobe(    "you@yourlogin.com",      # MessageGlobe login username    "XX|your-api-token",      # API token, used as the SMTP password    "no-reply@yourapp.com",    "YourApp",) client = EmailClient(config)
Explore the Email API

Error handling

One base type to catch

Every error raised by the SDK derives from a common type: handle them all in one place, or tell them apart case by case.

Python
from messageglobe import ApiError, MessageGlobeError, ValidationError try:    client.send(sms)except ValidationError:    # Client-side validation failed    ...except ApiError as exc:    # The API returned an error    print(exc.message)            # "Invalid params"    print(exc.api_error_code)     # 200    print(exc.http_status_code)   # 422    print(exc.errors)except MessageGlobeError:    # Any other SDK error    ...
TypeRaised when
ConfigurationErrorConfiguration is missing or invalid.
ValidationErrorA message or a contact fails client-side validation.
ApiErrorA REST endpoint (SMS, Contacts, Lists, Sender IDs) returns an error.
TransportErrorNetwork failure, timeout or an undecodable response.
EmailErrorSMTP delivery fails.

Base type shared by every error: MessageGlobeError

HTTP client

Use your own network stack

Every REST client uses a dependency-free default transport. You can swap in your own — handy for tests, for adding retries, or for reusing your application's HTTP stack.

Python
import requests from messageglobe import HttpResponse  class RequestsHttpClient:    def request(self, method, url, headers=None, body=None):        response = requests.request(method, url, headers=dict(headers or {}), data=body)         return HttpResponse(            status_code=response.status_code,            body=response.text,            headers=dict(response.headers),        )  client = SmsClient(config, RequestsHttpClient())

Other SDKs

Same API, other languages

The official SDKs are feature-aligned: the language changes, the workflow does not.

Ready to integrate?

Open an account, generate your API token and send your first message in minutes.

MessageGlobe Support

Fill in the form and we'll reply as soon as possible.

Checking agent availability…