Sending SMS from Python with Google Cloud Functions
Last Updated :
24 Apr, 2025
In this article, we are going to talk about how we are going to send SMS (Short Message Services) with the addition of the Powers of Google Cloud Functions. Combining it with Twilio which is a cloud communications platform that provides APIs for sending and receiving SMS messages, as well as other communication channels like voice calls and video will help us to create a "serverless" solution for sending SMS messages.
Setting up your Google Cloud Project
Step 1: Sign in with your Google Account in Google Cloud (Type Google Cloud and then search for Console, NOT the topmost link)Or you can skip the account creation as It requires Card information and tax details some of you might not have them
Step 2: Create a new Project, If you are a new user it should create a default project by itself, if not. Creating project It will look Something like this
Output of Cloud pageStep 3: Now you will be welcomed to the console of the Google Cloud with your project name. Now select the 3 dots (Navigation Menu) which will have all the necessary APIs.

Step 4: Now In the Navigation menu select the API & Services and then select Libary in the drop-down menu.

Step 5: Now Search for "Cloud Pub/Sub" API not to be confused with "Pub/Sub lite API", click on it and press activate
Step 6: Now you might see this after activating the "Cloud Pub/Sub" API.
Don't Panic No money is required (Thnx!)Step 7: Now you just need to fill up your credentials, for our project we need to select these options

Step 8: Click Next and Create your Service Account Name, Service ID will be automatically generated. Now grant the Service Account Cloud Pub/Sub Service Agent to your service account as his role.Now Grant admin access to your Gmail account, this makes it so that in the future you can access this service account. Your Policy will be updated. Now go and search for "Cloud Functions API" Activate it and you are golden!
Step 9: From Nevagation Menu select "IAM & Admin" and click on "Service Accounts" Find the service account for which you want to generate the JSON key file and click on it. In the service account details page, click on the "Manage Keys" tab from Action (three dots thingy) "Click" on Add key and select "Create new key". JSON file will have been downloaded in your system. It contains many sensitive informations.
Step 10: Now we will be requiring to create Topic for your project, you will be required to go to Pub/Sub in Analytic section, nevigate to "Topics" and there you will find this option
Create TopicAfter creating your "Topic" Click on the newly created Topic ID it will redirect you to "Topic name", now copy that "Topic name"

After Setting up your Google Cloud Project, You set up your Twilio account with thee help os given instructions.
Setting Up your Twilio Account
- Go to Twilio and Sign in after which you will find fue important Informations.
- After Signing in select "Get your number" to get your new Twilio number and also copy your "Account SID" and "Auth Token"and then we will move on to the coding.
Python code for sending messages
Step 1: First we need to install the necessary packages.
Python3
pip install twilio
pip install google-cloud-pubsub
Step 2: Next we need to write the following code. Remember that JSON file that we just downloaded!, now copy and locate your JSON file and then type in the following code along with your other credentials
Python3
from twilio.rest import Client
from google.cloud import pubsub_v1
import os
# Your JSON file location
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] =
'/path/to/your/credentials/filename.json'
# Twilio account credentials
account_sid = 'YOUR TWILIO ACCOUNT SID'
auth_token = 'YOUR TWILIO AUTH TOKEN'
# Twilio phone number and target phone number
twilio_number = 'YOUR TWILIO NUMBER'
# Give full phone number without spacking and also specify your country code
target_number = 'YOUR REGISTERED PHONE NUMBER WITH TWILIO'
# Create a Twilio client
client = Client(account_sid, auth_token)
# Create a Pub/Sub publisher client
publisher = pubsub_v1.PublisherClient()
# Define the Pub/Sub topic name
topic_name = 'projects/your-project-id/topics/your-topic-name'
def send_sms(sender, recipient, message):
# Send the SMS using Twilio
client.messages.create(
body=message,
from_=sender,
to=recipient
)
print("SMS sent successfully.")
def publish_message(message):
# Publish a message to the Pub/Sub topic
message_data = message.encode()
future = publisher.publish(topic_name, data=message_data)
print("Message published to Pub/Sub. Message ID:", future.result())
if __name__ == "__main__":
# Send the SMS using Twilio
send_sms(twilio_number, target_number,
'Thank you for using geeksforgeeks!')
# Publish a message to the Pub/Sub topic
publish_message('Thank you for using geeksforgeeks!')
Output:
SMS you will receive in your phone
This Python code will deliver a Message to your Target Phone number and then it will also Publish a message to the Pub/Sub topic, you can always change your message replace it with a link . Now If we look into the Topic in the Google Cloud services we can find this,
Output in Google Cloud ServicePython code which can send SMS which can be monitered using Google cloud and it can pull messages in Google Cloud By going in Pub/Sub, By Creating Subscription( Good to know that all the published message are stored in the topic until a subscriber subscribes to the topic and acknowledges receipt of the message.Or the message will die after 7 days).
Visualizing the dataConclusion
We can deploy our code using Cloud Function using the Inline editor Once your function is deployed, you can test it by sending it an HTTP request. The URL for your function is in the output of the deployment command, you could use this approach to send marketing messages, to send notifications, or to integrate with other applications. One another mportant thing to remember is that Google Cloud Pub/Sub is commonly used in app or web applications where there is a need for a messaging pipeline or event-driven architecture, It is useful when we have to perform and keep records of multiple functions or works.
Similar Reads
How to Use Google Cloud Function with Python ?
Google Cloud Functions provides a way to run small pieces of code in response to cloud events without managing servers. If you're a developer looking to automate tasks, process data or build APIs, Python is a great language for working with Google Cloud Functions.In this article, we will look into h
6 min read
Cloud Computing with Python
Cloud services offer on-demand computing resources, making applications more scalable, cost-effective and accessible from anywhere.Python has become one of the most popular programming languages for cloud computing due to its simplicity, flexibility and vast ecosystem of libraries. Whether youâre de
5 min read
Setting up Google Cloud SQL with Flask
Setting up a database can be very tricky, yet some pretty simple and scalable solutions are available and one such solution is Google Cloud SQL. Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, and administer your relational PostgreSQL and MySQL databases in the
6 min read
Send an SMS Message with Python
In today's fastest-growing world, SMS is still a powerful tool by which we can reach billions of users and one can establish a connection globally. In this new world when instant messaging and social media are dominating you can feel our humble SMS outdated but you don't underestimate its power, it
4 min read
Returning a function from a function - Python
In Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior.Example:Pythondef fun1(name): def fun2(): return f"Hello, {name}!" return fun2 # Get the
5 min read
How to Automate Google Sheets with Python?
In this article, we will discuss how to Automate Google Sheets with Python. Pygsheets is a simple python library that can be used to automate Google Sheets through the Google Sheets API. An example use of this library would be to automate the plotting of graphs based on some data in CSV files that w
4 min read
How to do Cloud File Sharing using Python?
In this article, we will see how to share files online using a free, secure platform called GoFile. We can make it available for anyone through the link generated with the help of Python. Gofile is a platform for sharing and storing files. You have no restrictions on how much content you can save or
4 min read
Uploading files on Google Drive using Python
In the modern era of the internet, a large number of mundane or work-related tasks are carried out over the internet. Compromise of data stored on a device could cause massive harm to an individual/company. Considering the rise in the number of malware, viruses, worms, trojan horse etc the security
3 min read
Cloud Functions in GCP
Cloud Functions are a serverless computing service offered by Google Cloud Platform (GCP). They provide a simple way to run code in response to events with minimal configuration and maintenance. Cloud Functions are event-driven, meaning they can be triggered by events such as changes in data, new me
5 min read
Send mail with attachment from your Gmail account using Python
In last article, we have discussed the basics of sending a mail from a Gmail account without any subject as well as without any attachment. Today, we will learn how to send mail with attachment and subject using Python. Before moving on, it is highly recommended to learn how to send a simple mail us
4 min read