Python通过USB串口发送许多短信

时间:2015-08-30 16:13:31

标签: python mysql for-loop sms

我现在真的迷失在这个需要向多个收件人发送短信的部分。

如何向我数据库中的所有联系人发送短信?我是否使用for-loops?或者还有其他方法吗?非常感谢你。

这是我的短信代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
import time
import sys
import MySQLdb as mdb

try:
    con = mdb.connect('localhost', 'user', 'password', 'db')
    print 'Database connected';
except Exception as e:
    sys.exit('Database connection failed')

cur = con.cursor()
cur.execute("Select contacts from dbtable")
con.commit()
number= cur.fetchall()
print number

for item in number:
    recipient= recipient+item

class TextMessage:
    def __init__(self, recipient="xxxxxxxx",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/ttyUSBSMS', 460800, timeout=5, xonxoff = False, rtscts = False, bytesize = serial.EIGHTBITS, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE)
        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()

sms = TextMessage("xxxxxxxx","Important!")
sms.connectPhone()
sms.sendMessage()
sms.disconnectPhone()
print "message sent successfully"

打印输出

(('99876545',), ('87546412',), ('97789546',), ('87546464',), ('97377454',))

1 个答案:

答案 0 :(得分:0)

一个简单的for循环可以完成这项任务:

t_list =  (('99876545',), ('87546412',), ('97789546',), ('87546464',), ('97377454',))

for t in t_list:
    number = t[0]
    print(number)
    # Call function to send SMS to the given `number`

只需调整这种基本方法即可满足您的需求。