Python 发送阿里云手机短信消息

一般用于发送验证码,本代码实现功能如下:

1、联接MsSqlServer获取短信任务清单,这个可以业务系统往该表插数据

2、根据阿里云短信息的相关信息(appid,secret,消息模板),发送手机消息

3、创建定时任务,监听消息任务

python 复制代码
from datetime import datetime
import time
import threading
from queue import Queue
from queue import Empty
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import pymssql


class SmsServer(object):
    

    def init(self):
        #self.connect = pymssql.connect('xx.xx.x.xx:6229', 'xx', 'xx', 'HD_Common')  #建立连接
        self.connect = pymssql.connect('xx:6229', 'xx', 'xx', 'HD_Common')  #建立连接
        if self.connect:
            print("连接成功!")

    def send(self,mobile, code):

        client = AcsClient('LTAI4G1JqvT6xp8vE***', 'y5L5cm1FJEKhvG6N932IwSYP***', 'cn-hangzhou')

        request = CommonRequest()
        request.set_accept_format('json')
        request.set_domain('dysmsapi.aliyuncs.com')
        request.set_method('POST')
        request.set_protocol_type('https') # https | http
        request.set_version('2017-05-25')
        request.set_action_name('SendSms')

        request.add_query_param('RegionId', "cn-hangzhou")
        request.add_query_param('PhoneNumbers', mobile)
        request.add_query_param('SignName', "**汽车")
        request.add_query_param('TemplateCode', "SMS_211*****")
        request.add_query_param('TemplateParam', '{\"code\":\"'+ code +'\"}')

        response = client.do_action(request)
        # python2:  print(response)
        print(str(response, encoding = 'utf-8'))
        pass

    def sendSms(self):
        cursor = self.connect.cursor()   #创建一个游标对象,python里的sql语句都要通过cursor来执行
        sql = "select id,phone,code from s_sms where status = 0"
        cursor.execute(sql)   #执行sql语句
        row = cursor.fetchone()  #读取查询结果,
        while row:              #循环读取所有结果

            id = row[0]
            mobile = row[1]
            code = row[2]
            print("发送短信给"+ mobile +",code=" + code)
            self.send(mobile,code)
            self.updateSms(id)
            row = cursor.fetchone()
        
    def updateSms(self,id):
        cursor = self.connect.cursor()   
        cursor.execute(f"update s_sms set status=1,sendtime=getdate() where id={id}")  
        self.connect.commit()  #提交
        

    # 每n秒执行一次
    def job(self):
        while True:
            print(datetime.now().strftime("%Y-%m-%d  %H:%M:%S"))
            try:
                self.sendSms()
                time.sleep(3)      
            except Exception as reason:
                print(reason)
                
        
smsServer = SmsServer()
smsServer.init()
smsServer.job()
相关推荐
灵智工坊LingzhiAI2 小时前
人体坐姿检测系统项目教程(YOLO11+PyTorch+可视化)
人工智能·pytorch·python
烛阴9 小时前
简单入门Python装饰器
前端·python
好开心啊没烦恼10 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
面朝大海,春不暖,花不开10 小时前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
2301_8050545611 小时前
Python训练营打卡Day59(2025.7.3)
开发语言·python
万千思绪11 小时前
【PyCharm 2025.1.2配置debug】
ide·python·pycharm
微风粼粼13 小时前
程序员在线接单
java·jvm·后端·python·eclipse·tomcat·dubbo
云天徽上13 小时前
【PaddleOCR】OCR表格识别数据集介绍,包含PubTabNet、好未来表格识别、WTW中文场景表格等数据,持续更新中......
python·ocr·文字识别·表格识别·paddleocr·pp-ocrv5
你怎么知道我是队长14 小时前
python-input内置函数
开发语言·python
叹一曲当时只道是寻常14 小时前
Python实现优雅的目录结构打印工具
python