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()
相关推荐
旋生万物17 分钟前
素数都排在等角螺线上?用螺旋数论给黎曼猜想画一张“几何画像“(附Python)
python·ai编程·数论·黎曼猜想·素数分布
用户37215742613531 分钟前
使用 Python 压缩 PDF 文件:减小图片、字体和文档内容体积
python
java1234_小锋34 分钟前
Tornado 6.5,全面支持 Python 3.14
数据库·python·tornado
IT毕设梦工厂1 小时前
计算机毕业设计选题推荐:基于大数据的印度上市公司财务指标数据可视化分析|毕业设计选题|计算机毕设|选题推荐|毕设指导|项目定制|源码|高质量项目
大数据·hadoop·python·信息可视化·spark·课程设计·大数据毕设项目
SEO_juper1 小时前
你的服务器正在被 AI 爬虫“白嫖“带宽:2026 用日志把 Googlebot 和 AI 洪流分开算账(附脚本)
运维·人工智能·爬虫·python·chatgpt·seo
浩风祭月1 小时前
GPT Image 2.5 Sunburst还是Flare?模型选型、Python接入与成本避坑
python·aigc·openai·图像生成·gpt image 2.5
泡干脆面就番茄1 小时前
03_LBPH人脸识别算法原理与实战
python·opencv
Yanjun2i1 小时前
Agent学习记录四:多工具时如何处理
人工智能·python·学习·agent
李少兄2 小时前
Java 中只有值传递吗?
java·开发语言·python
名字还没想好☜2 小时前
Spring @EventListener 事件驱动解耦实战:同步转异步、事务绑定与顺序控制
java·数据库·后端·python·spring