Python code for sending SMS messages via a USB connected mobile phone

I have a spare mobile phone (Samsung G600 to be exact) and I though it would be nice to use this phone for text alerts, be it system down, download complete, whatever. I also have a data cable with my phone meaning that this shouldn't be too difficult. So I started searching the web for way's in which to do this. There are many many mobile apps out there and many things claiming to be able to do what I want but nothing seemed to work. Then I realised that a mobile phone is effectively a modem, and that the AT commands might be able to do this.

I stumbled across an article on Design Build Test Repeat which showed how to do this using a 3G USB dongle and went from there.

I basically took the code from the above link and modified it to suite my needs. The code in the above example didn't work but it did appear to be the best starting point. I ended up having to add the sleep(1) "commands" because without them the phone wouldn't send any messages. The AT commands were being sent too quickly.

Here is the resulting code.

#!/usr/bin/env python
"""
sms.py - Used to send txt messages.
"""
import serial
import time
 
class TextMessage:
    def __init__(self, recipient="0123456789", message="TextMessage.content not set."):
        self.recipient = recipient
        self.content = message
 
    def setRecipient(self, number):
        self.recipient = number
 
    def setContent(self, message):
        self.content = message
 
    def connectPhone(self):
        self.ser = serial.Serial('/dev/ttyACM0', 460800, timeout=5)
        time.sleep(1)
 
    def sendMessage(self):
        self.ser.write('ATZ\r')
        time.sleep(1)
        self.ser.write('AT+CMGF=1\r')
        time.sleep(1)
        self.ser.write('''AT+CMGS="''' + self.recipient + '''"\r''')
        time.sleep(1)
        self.ser.write(self.content + "\r")
        time.sleep(1)
        self.ser.write(chr(26))
        time.sleep(1)
 
    def disconnectPhone(self):
        self.ser.close()

And it's called like this:

sms = TextMessage("0123456789","This is the message to send.")
sms.connectPhone()
sms.sendMessage()
sms.disconnectPhone()
Micro Banner Micro Banner Micro Banner Micro Banner Micro Banner Micro Banner