Blog

How to send SMS with Python

Tautvydas Tijūnaitis Tautvydas Tijūnaitis
· 6 min read · Tips and resources · February 14th, 2024
Sending SMS with Python offers a versatile approach to communication automation in your application. What’s more, you can streamline the implementation process with a reliable SMS delivery platform, like MailerSend.

SMS integration is significant for applications requiring timely notifications, such as two-factor authentication (2FA), appointment reminders, order cancellations and confirmations, or even emergency alerts. 

So, if you want to implement the delivery of these types of messages for your app or website, you’ve come to the right place. This article intends to give an in-depth guide to Python developers on how to send SMS with the MailerSend platform.

Prerequisites

Before you begin sending SMSes with MailerSend, make sure you have the following in place:

  • Python 3.6^: Ensure that you have Python 3.6 and above with the pip module installed on your local machine. You can download Python from the official website

  • MailerSend account: To send SMS using MailerSend, you'll need to create an account on the MailerSend platform and upgrade to one of the paid plans, all of which include a number of SMSes. Check out the pricing and sign up here

  • MailerSend phone number: If you don't have one you can learn how to get one here. Paid accounts are assigned a trial phone number that can be used to test out SMS-sending capabilities.

Getting Started

MailerSend offers a simple SMS API and advanced features to make sending text message notifications simple. Once you’ve created an account and purchased a phone number (or if you’re using the trial phone number for testing), you’ll need to retrieve your API keys. You can learn more about creating API tokens in our guide. 

Remember: Keep API keys secure and never expose them in public repositories.

How to send an SMS

To use MailerSend to send an SMS using Python, first install the MailerSend Python library. You can do this by running the following command in your console:

```bash
pip install mailersend
```

The MailerSend Python SDK will be installed on your local system after the command has been executed. Next, in your project directory, create a file called `send_sms.py` and paste the following code into it:

```python
from mailersend import sms_sending

api_key = "MAILERSEND_API_KEY"

mailer = sms_sending.NewSmsSending(api_key)

# Number belonging to your account in E164 format
number_from = "YOUR_MAILERSEND_NUMBER"

# recipient's number
numbers_to = [RECIPIENT_NUMBER]

text = "This is the text content"

print(mailer.send_sms(number_from, numbers_to, text))
```

The `sms_sending` class will have been first imported from the MailerSend module. Following that, define the API key you retrieved from MailerSend, as well as your MailerSend toll-free number. The number must be in E164 format. 

Then specify the recipient's phone number and the text you want to send. The variable `number_to` is an array that can store up to 50 numbers. Finally, the `send.sms` method from the `sms_sending` class is invoked.

Run the script in the console by executing the below command into the project's PWD:

```bash
python send_sms.py
```

If you’ve entered everything correctly, the above command will send the SMS message to the number that you entered into the `number_to` variable, returning only the message ID.

Sending SMS with Python use case examples

There are countless scenarios in which sending SMS would be useful when working with a web application. Let's look at a couple of examples to see how it works. 

Imagine a service that offers appointment scheduling for hair salons. In addition to the scheduling functionality, they also implement automated SMS reminders to minimize no-shows and boost client engagement. Here's some sample code you can use to send such an appointment reminder with MailerSend:

```python
from mailersend import sms_sending 

api_key = "MAILERSEND_API_KEY"  

mailer = sms_sending.NewSmsSending(api_key)

number_from = "YOUR_MAILERSEND_NUMBER"

number_to = '+1234567890'

text = "Your appointment is scheduled for tomorrow at 10 AM. See you there!"

print(mailer.send_sms(number_from, number_to, text))

```

Another popular use for transactional SMS is for sending one-time passwords (OTPs) to authenticate users in your application. To send an OTP, the code would look something like this:

```python
from mailersend import sms_sending 
from random import randint

api_key = "MAILERSEND_API_KEY"  

mailer = sms_sending.NewSmsSending(api_key)

number_from = "YOUR_MAILERSEND_NUMBER"
number_to = "+1234567890"
code = str(randint(1000, 9999))

text = "Hi, there. Your authentication code is {{code}}. Please do not share this code. Thank you."

personalization = [
    {
        "phone_number": number_to,
        "data": {
            "code": code
        }
    }
]
print(mailer.send_sms(number_from, number_to, text, personalization))
```

Transactional SMS tips and best practices

Compliance with local rules and industry standards is critical while sending SMS messages. There are government rules and procedures in place that detail how to send SMS messages. Failure to follow these regulations may result in legal consequences and harm to your reputation. Here are some best practices and tips:

Obtain the appropriate consent 

Before sending an SMS, ensure you have explicit consent from recipients. You must also provide a means for recipients to opt out of receiving your text messages to comply with MailerSend's terms of service and the Cellular Telecommunications Industry Association's (CTIA) requirements.

Use a valid sender number

Make sure you send your text messages from a working phone number to guarantee error-free delivery and the greatest experience for the receivers. The number needs to be active on your account.

Verify your number in MailerSend

When you purchase a new phone number, you’ll need to verify it. This involves providing some details about your company and how you plan to use SMS. This is purely to protect our users and prevent abuse of the system. Without verifying your phone number, you won’t be able to send any SMS. 

Use the E164 format

You must use the E164 format when inputting recipient and sender phone numbers. This has a maximum of 15 digits. The numbers begin with a plus sign (+), then the mobile number and the country code (for example,+44 for the United Kingdom).

Keep it SHAFT-free 

SHAFT is a CTIA-created regulation that forbids businesses from transmitting any material that advocates or contains sexual content, hate speech, alcohol, firearms, or tobacco. There are certain exceptions: businesses selling tobacco or alcohol must employ age-gating to safeguard underage customers and keep them from consenting to SMS marketing.

Check out our guide on SMS compliance to learn more about different types of SMS, the consent needed for each one, and more in-depth best practices.

Sending SMS with Python is simple

You now know how to easily combine Python with MailerSend for SMS. It’s actually pretty straightforward—you can instantly send your recipients an SMS message with only a few lines of code. And, although you might be eager to start sending right away, we highly recommend you familiarize yourself with SMS compliance best practices first to ensure the best user experience.

Have you sent text messages with Python? We'd love to hear your tips, tricks, and recommendations in the comments.

Tautvydas Tijūnaitis
I'm Tautvydas, Lead Developer at MailerSend. When I'm not busy coding, I live and breathe European football—whether watching games in stadiums or building my fantasy team online!