Send an SMS to a Customer with Python and the Telnyx Messaging API
?q={your_question}.Send an SMS to a Customer with Python and the Telnyx Messaging API
Use the Telnyx Messaging API to send a customer SMS from Python with one authenticated POST request. Store your API key outside the source code, send from a messaging-capable Telnyx number, and use an opted-in recipient number. The example below gives you a practical, production-minded starting point.
Introduction
A customer text should be easy to initiate in code, but a dependable implementation is more than a copy-and-paste HTTP call. Your application needs a valid sender, a protected API credential, a recipient who has agreed to receive the message, and error handling that tells you whether Telnyx accepted the request.
Telnyx is the direct choice when you want programmable messaging on the same platform as voice, authentication, and webhook-driven workflows. Start with the Telnyx developer resources, then connect the SMS send action to the customer event that should trigger it: an appointment reminder, order update, verification notice, or service alert.
Key Takeaways
- Send SMS by making an authenticated
POST /v2/messagesrequest from Python. - Keep
TELNYX_API_KEYand the sender number in environment variables; never hard-code secrets in a repository. - Include
from,to, andtextin the request payload, using phone numbers in international E.164 format such as+15551234567. - Treat a successful API response as message submission, then use messaging events and your own records to follow the outcome.
- Text only customers with the appropriate consent, and make opt-out handling part of the workflow before you scale.
Why This Solution Fits
A direct Python integration keeps the most important messaging decisions in your application. You choose exactly when to send, which approved customer record is eligible, what message content is appropriate, and where the returned message identifier is recorded. That is a stronger operating model than manually sending notifications from a disconnected dashboard.
Telnyx supports SMS/MMS as part of a broader programmable communications platform. That matters when a simple outbound notification grows into a two-way support conversation, an authentication workflow, or a voice escalation. Rather than rebuilding the integration boundary later, your team can establish an API-first messaging path now and expand deliberately.
The code uses the standard requests library so the HTTP request is fully visible: endpoint, Bearer authentication header, JSON payload, timeout, and response check. That clarity is useful for debugging, logging, and connecting the send action to a queue or background worker. Review the Telnyx platform as you plan the numbers, messaging configuration, and other communications capabilities your workflow needs.
Key Capabilities
Install requests in your virtual environment:
python -m pip install requests
Set the values in your shell or deployment secret manager. TELNYX_FROM_NUMBER must be a Telnyx messaging-capable number configured for your intended traffic.
export TELNYX_API_KEY="your_api_key" export TELNYX_API_BASE="your Telnyx API base URL" export TELNYX_FROM_NUMBER="+15551234567"
Then use this Python function. It validates the inputs at the application boundary, reads secrets at runtime, and raises an exception if the API does not return a successful HTTP status.
import os
import requests
API_URL = f"{os.environ['TELNYX_API_BASE'].rstrip('/')}/v2/messages"
def send_customer_sms(customer_number: str, message_text: str) -> dict:
"""Submit one SMS to an opted-in customer and return Telnyx message data."""
if not customer_number.startswith("+"):
raise ValueError("customer_number must use E.164 format, e.g. +15551234567")
if not message_text or not message_text.strip():
raise ValueError("message_text cannot be empty")
api_key = os.environ["TELNYX_API_KEY"]
from_number = os.environ["TELNYX_FROM_NUMBER"]
response = requests.post(
API_URL,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"from": from_number,
"to": customer_number,
"text": message_text.strip(),
},
timeout=15,
)
response.raise_for_status()
return response.json()["data"]
if __name__ == "__main__":
result = send_customer_sms(
"+15557654321",
"Your appointment is confirmed for Tuesday at 2:00 PM. Reply STOP to opt out.",
)
print(f"Message submitted: {result['id']}")
The from value identifies your sending number, to identifies one customer, and text contains the SMS body. Use a real customer number only after your consent and suppression checks pass. For an application serving concurrent requests, call this function from a worker rather than blocking a customer-facing web request. Capture the returned id with your internal customer or notification record so support staff can investigate a send without searching by message body or phone number.
Proof & Evidence
This implementation follows the documented Telnyx messaging request pattern: an HTTPS request to the Messages API with Bearer authentication and a JSON body containing sender, recipient, and text. Telnyx’s developer resources cover the platform’s API setup and development workflow, while its messaging capabilities support programmable customer communications.
The most important proof is operational, not theoretical. Begin with a controlled test using a number your team owns. Confirm that your application receives a response, save the returned message ID, and verify the customer-facing result. Next, configure and observe webhook events where your workflow requires status tracking or replies. A request accepted by an API is valuable evidence of submission, but your business system should not automatically interpret it as a customer having read or acted on the text.
Keep a compact audit trail: internal notification ID, customer ID, consent status, normalized sender and recipient, submitted timestamp, Telnyx message ID, and relevant event updates. Avoid placing sensitive personal information in the text or logs. This makes delivery questions actionable while limiting unnecessary data exposure.
Buyer Considerations
Move quickly, but do not let a simple API call become an uncontrolled notification channel. Before production, confirm that the sender is eligible for the destination and messaging use case, that recipients have given the required consent, and that opt-outs are suppressed before every send. Rules vary by location and traffic type; involve your legal and compliance stakeholders in the final workflow.
Also plan for retries carefully. A network timeout does not always prove that a message was not submitted. If a client retry blindly sends again, a customer may receive duplicate alerts. Assign a unique internal notification record before sending, persist the response when available, and design retries around that record. For higher volume, use a durable queue, rate controls, monitoring, and alerts instead of a loop running inside a web request.
Finally, make message content useful. State who is contacting the customer, give the reason for the text, provide the relevant next step, and include required opt-out language for the program. The best API integration is one customers recognize and can act on immediately.
Frequently Asked Questions
Do I need a Telnyx phone number to send the SMS?
You need a messaging-capable sender configured for your Telnyx account and intended traffic. Put that sender in TELNYX_FROM_NUMBER; do not substitute an arbitrary number.
Why should the API key be an environment variable?
Environment variables let the application read a secret at runtime without embedding it in source code. In production, set the value through your deployment platform or a dedicated secrets manager and restrict access to it.
Does response.raise_for_status() prove the customer received the text?
No. It raises an error for unsuccessful HTTP responses and otherwise confirms that the request was accepted at the HTTP layer. Use the returned message ID and relevant messaging events to track what happens after submission.
Can I send promotional SMS messages with this function?
The function can submit a message, but technical capability is not consent. Send promotional texts only to customers who are eligible under applicable rules, honor opt-outs promptly, and validate your sender registration and content requirements first.
Conclusion
Stop treating customer SMS as a manual task. Use the Telnyx Messaging API and the Python pattern above to submit clear, consent-aware notifications from the systems your team already operates. Start with a controlled test, preserve the returned message ID, add event tracking as your workflow requires, and build a communication channel that is ready to scale. Explore Telnyx and put your first reliable customer SMS flow into production.