• Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

    Building a Network Tracker Auditor for Privacy with Python

    Building a Network Tracker Auditor for Privacy with Python

    Streaming Audio Files Securely with PHP

    Streaming Audio Files Securely with PHP

    Scraping Web Data with Python Helium

    Scraping Web Data with Python Helium

    Building a Secure 2FA Authenticator with Python

    Building a Secure 2FA Authenticator with Python

    Building a Cache Warmer with Python

    Building a Cache Warmer with Python

    How to Create a Python GUI to Launch Webhooks

    How to Create a Python GUI to Launch Webhooks

    Mastering python-docx A Guide to Creating Word Documents with Python

    Mastering python-docx: A Guide to Creating Word Documents with Python

  • Blog
    • All
    • Artificial Intelligence
    • Privacy
    • Reviews
    • Security
    • Tutorials
    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

    38 essential points to harden WordPress

    38 Essential Points to Harden WordPress

    10 Tips and Tricks to Secure Your WordPress Website

    10 Tips and Tricks to Securing Your WordPress Website

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Technical Support
No Result
View All Result
  • Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

    Building a Network Tracker Auditor for Privacy with Python

    Building a Network Tracker Auditor for Privacy with Python

    Streaming Audio Files Securely with PHP

    Streaming Audio Files Securely with PHP

    Scraping Web Data with Python Helium

    Scraping Web Data with Python Helium

    Building a Secure 2FA Authenticator with Python

    Building a Secure 2FA Authenticator with Python

    Building a Cache Warmer with Python

    Building a Cache Warmer with Python

    How to Create a Python GUI to Launch Webhooks

    How to Create a Python GUI to Launch Webhooks

    Mastering python-docx A Guide to Creating Word Documents with Python

    Mastering python-docx: A Guide to Creating Word Documents with Python

  • Blog
    • All
    • Artificial Intelligence
    • Privacy
    • Reviews
    • Security
    • Tutorials
    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

    38 essential points to harden WordPress

    38 Essential Points to Harden WordPress

    10 Tips and Tricks to Secure Your WordPress Website

    10 Tips and Tricks to Securing Your WordPress Website

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Technical Support
No Result
View All Result
Home Guides Programming Python

Simplifying SMS Alerts with Python and SMTP

Jonathan Moore by Jonathan Moore
2 years ago
Reading Time: 6 mins read
A A
Simplifying SMS Alerts with Python and SMTP
FacebookTwitter

Whether it’s for emergency notifications or simple reminders, sending SMS alerts is a powerful way to get your message across. In this article, we will break down a Python code that simplifies the process of sending SMS alerts via email. We’ll dissect the code, explaining each section to help you understand how it works and how you can customize it to suit your needs.

Code Overview

The provided Python script enables you to send SMS alerts by leveraging the Simple Mail Transfer Protocol (SMTP). Before diving into the code itself, let’s first look at the key components involved:

  • SMTP (Simple Mail Transfer Protocol): This is the standard protocol used for sending electronic mail (email) on the Internet. We’ll use it to deliver our SMS alerts.
  • Carrier Gateways: Different mobile carriers provide email gateways that allow sending messages to a recipient’s phone number via email. These gateways vary from carrier to carrier and are a critical part of this solution.
  • Python Script: The Python script serves as the bridge between your message and the recipient’s mobile phone. It takes care of formatting the message correctly and using the SMTP protocol to deliver it.

Let’s dive into the code to see how all of this comes together.

Importing Libraries

#!/usr/bin/python3
import smtplib
import ssl

We begin by importing two important libraries: smtplib and ssl. smtplib is a Python library that provides an interface to send emails using the SMTP protocol. We also import ssl to create a secure SSL context for the SMTP connection. Secure connections are essential to protect sensitive information, such as email credentials.

Carrier Gateways

# Define the carrier gateways in a more readable way using a dictionary.
carrier_gateways = {
    "AT&T": "@txt.att.net",
    "Boost Mobile": "@myboostmobile.com",
    "Cricket": "@sms.mycricket.com",
    "Metro PCS": "@mymetropcs.com",
    "Sprint": "@messaging.sprintpcs.com",
    "T-Mobile": "@tmomail.net",
    "Tracfone": "@mmst5.tracfone.com",
    "US Cellular": "@email.uscc.net",
    "Verizon": "@vtext.com",
    "Virgin Mobile": "@vmobl.com",
}

This section defines a dictionary named carrier_gateways. It associates mobile carrier names with their corresponding email gateways. Using a dictionary provides a clean and readable way to map carriers to their gateways, making it easy to look up the gateway for a specific carrier later in the code.

SMTP Configuration

SMTP_EMAIL    = "nobody@mysite.com"
SMTP_PASSWORD = "myPassword23"
SMTP_SERVER   = "mail.mysite.com"
SMTP_PORT     = 465

Here, we set up the SMTP server configuration. These are the necessary parameters to connect to your email server securely:

  • SMTP_EMAIL: Your email address.
  • SMTP_PASSWORD: Your email password.
  • SMTP_SERVER: The SMTP server’s hostname.
  • SMTP_PORT: The port number for the SMTP server. In this case, it’s 465, which is the standard port for SMTP over SSL.

It’s important to keep your email credentials safe and not hardcode them in your script for security reasons. You may want to explore environment variables or a configuration file for a more secure approach.

Sending SMS Alerts

def send_sms_alert(carrier, phone_number, subject, message):
    if carrier in carrier_gateways:
        gateway = carrier_gateways[carrier]

        body = message
        message = f"Subject: {subject}\n\n{body}"

        try:
            context = ssl.create_default_context()
            with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, context=context) as server:
                server.login(SMTP_EMAIL, SMTP_PASSWORD)
                server.sendmail(SMTP_EMAIL, phone_number + gateway, message)
                print(f"SMS sent to {phone_number} via {carrier}!")
        except smtplib.SMTPException as e:
            print(f"An error occurred: {e}")
    else:
        print("Carrier not found in the dictionary. Please provide a valid carrier name.")

This is the heart of the script. The send_sms_alert function takes four parameters: carrier, phone_number, subject, and message. It is responsible for sending the SMS alert.

Here’s a step-by-step breakdown of how it works:

  1. Carrier Validation: The function checks if the provided carrier exists in the carrier_gateways dictionary. If the carrier is not found, it prints an error message. This step ensures that the script can only send SMS alerts to supported carriers.
  2. Gateway Lookup: If the carrier is found, it looks up the corresponding email gateway in the carrier_gateways dictionary.
  3. Message Formatting: The message is combined with the subject and formatted into an email message. The Subject header is used to set the SMS subject, while the message body contains the actual content.
  4. Sending the SMS:
    • It creates an SSL context to secure the connection.
    • Opens a connection to the SMTP server using the provided configuration.
    • Logs in using your email credentials (username and password).
    • Uses server.sendmail to send the formatted message to the recipient’s phone number by appending the email gateway.
    • Prints a success message when the SMS is sent.
  5. Error Handling: In case of any issues during the sending process, it catches smtplib.SMTPException and prints an error message.
  6. Carrier Not Found: If the provided carrier is not in the carrier_gateways dictionary, it prints an error message to inform the user.

Main Function

if __name__ == "__main__":
    carrier      = "AT&T"
    phone_number = "5555555555"
    subject      = "SMS Alert"
    message      = "This is an alert message."

    send_sms_alert(carrier, phone_number, subject, message

The main part of the script executes when the Python file is run. In this example, it demonstrates how to use the send_sms_alert function. The parameters are set with sample values:

  • carrier: The recipient’s carrier (e.g., “AT&T”).
  • phone_number: The recipient’s phone number.
  • subject: The subject of the SMS.
  • message: The content of the SMS.

You can customize these values to send SMS alerts tailored to your needs.

The Complete Python Script

Below is the complete code, including all the sections we’ve explained so far.

#!/usr/bin/python3
import smtplib
import ssl

# Define the carrier gateways in a more readable way using a dictionary.
carrier_gateways = {
    "AT&T": "@txt.att.net",
    "Boost Mobile": "@myboostmobile.com",
    "Cricket": "@sms.mycricket.com",
    "Metro PCS": "@mymetropcs.com",
    "Sprint": "@messaging.sprintpcs.com",
    "T-Mobile": "@tmomail.net",
    "Tracfone": "@mmst5.tracfone.com",
    "US Cellular": "@email.uscc.net",
    "Verizon": "@vtext.com",
    "Virgin Mobile": "@vmobl.com",
}

SMTP_EMAIL    = "nobody@mysite.com"
SMTP_PASSWORD = "myPassword23"
SMTP_SERVER   = "mail.mysite.com"
SMTP_PORT     = 465


def send_sms_alert(carrier, phone_number, subject, message):
    if carrier in carrier_gateways:
        gateway = carrier_gateways[carrier]

        body = message
        message = f"Subject: {subject}\n\n{body}"

        try:
            context = ssl.create_default_context()
            with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, context=context) as server:
                server.login(SMTP_EMAIL, SMTP_PASSWORD)
                server.sendmail(SMTP_EMAIL, phone_number + gateway, message)
                print(f"SMS sent to {phone_number} via {carrier}!")
        except smtplib.SMTPException as e:
            print(f"An error occurred: {e}")
    else:
        print("Carrier not found in the dictionary. Please provide a valid carrier name.")


if __name__ == "__main__":
    carrier      = "AT&T"
    phone_number = "5555555555"
    subject      = "SMS Alert"
    message      = "This is an alert message."

    send_sms_alert(carrier, phone_number, subject, message)

This complete script includes all the elements we’ve discussed in the previous sections. It defines the carrier gateways, sets up the SMTP configuration, and presents the send_sms_alert function for sending SMS alerts. Additionally, the script’s main section demonstrates how to use the function to send a sample SMS alert.

Customizing the Code

Now that you’ve understood the code’s structure and functionality, you can customize it to suit your specific requirements:

  • Adding More Carriers: If you want to support additional carriers, you can extend the carrier_gateways dictionary by mapping the carrier name to the respective email gateway.
  • Changing SMTP Configuration: Modify the SMTP configuration to match your email provider’s settings. Ensure you keep your credentials secure and consider using environment variables or configuration files.
  • Integration with Your Application: Instead of hardcoding the message parameters in the main function, integrate this script into your application. You can pass dynamic values to the send_sms_alert function to send alerts as needed.
  • Error Handling: Enhance the error handling to provide more informative messages and handle different types of exceptions if necessary.

Conclusion

In this article, we’ve explored a Python script that simplifies the process of sending SMS alerts via email, providing you with an efficient and versatile way to keep in touch with your audience. The script combines the power of Python, the SMTP protocol, and a well-defined dictionary of carrier gateways to send SMS messages reliably.

By breaking down the code and explaining its sections, I’ve given you a solid understanding of how it works. But the journey doesn’t end here. While this script is a solid starting point, the customization possibilities are nearly limitless, and you can adapt it to your unique use cases and requirements. Whether it’s for critical system alerts, customer notifications, or any other purpose, this script can be a valuable tool in your toolkit for effective communication.

Tags: PythonSMSSMTPLibSSL
ShareTweetSharePinShareShareScan
ADVERTISEMENT
Jonathan Moore

Jonathan Moore

Senior Software Engineer and Cybersecurity Specialist with over 3 decades of experience in developing web, desktop, and server applications for Linux and Windows-based operating systems. Worked on numerous projects, including automation, artificial intelligence, data analysis, application programming interfaces, intrusion detection systems, streaming audio servers, WordPress plugins, and much more.

Related Articles

Monitoring Web Page Changes with Python

Monitoring Web Page Changes with Python

There are times when I need to know that a web page has changed without actively watching it. That might...

Building a Network Tracker Auditor for Privacy with Python

Building a Network Tracker Auditor for Privacy with Python

In my last post, I dug into AdGuard, a robust ad blocker that tackles trackers and ads head-on. But how...

Scraping Web Data with Python Helium

Scraping Web Data with Python Helium

If you've ever needed to extract information from a website programmatically, you've likely heard of various tools and libraries. One...

Next Post
Understanding and Implementing ClamAV on Linux

Understanding and Implementing ClamAV on Linux

Recommended Services

Latest Articles

Monitoring Web Page Changes with Python

Monitoring Web Page Changes with Python

There are times when I need to know that a web page has changed without actively watching it. That might...

Read moreDetails

My SSH Setup: How I Manage Multiple Servers

My SSH Setup: How I Manage Multiple Servers

If you work with more than one server, the need to manage multiple servers with SSH becomes obvious pretty quickly....

Read moreDetails

Building a Network Tracker Auditor for Privacy with Python

Building a Network Tracker Auditor for Privacy with Python

In my last post, I dug into AdGuard, a robust ad blocker that tackles trackers and ads head-on. But how...

Read moreDetails

AdGuard Ad Blocker Review

AdGuard Ad Blocker Review

Ad blocking software has become essential for anyone who values a clean, fast, and secure browsing experience. With the ever-increasing...

Read moreDetails
  • Privacy Policy
  • Terms of Service

© 2025 JMooreWV. All rights reserved.

No Result
View All Result
  • Home
  • Guides
    • Linux
    • Programming
      • JavaScript
      • PHP
      • Python
    • Tools
    • WordPress
  • Blog
    • Artificial Intelligence
    • Tutorials
    • Privacy
    • Security
  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Technical Support