Python 发送短信

Python 发送短信

短信发送平台
在发送短信前需要添加两个配置文件,将下面两个文件复制下来即可
xmltojson.py


```# -*- coding: utf-8 -*-
# python xml.etree.ElementTree

import xml.etree.ElementTree as ET


# from xml.dom import minidom


class xmltojson:
    # global var
    # show log
    SHOW_LOG = True
    # XML file
    XML_PATH = None
    a = {
   }
    m = []

    def get_root(self, path):
        '''parse the XML file,and get the tree of the XML file
        finally,return the root element of the tree.
        if the XML file dose not exist,then print the information'''
        # if os.path.exists(path):
        # if SHOW_LOG:
        # print('start to parse the file : [{}]'.format(path))
        tree = ET.fromstring(path)
        return tree
        # else:
        # print('the path [{}] dose not exist!'.format(path))

    def get_element_tag(self, element):
        '''return the element tag if the element is not None.'''
        if element is not None:

            return element.tag
        else:
            print('the element is None!')

    def get_element_attrib(self, element):
        '''return the element attrib if the element is not None.'''
        if element is not None:

            return element.attrib
        else:
            print('the element is None!')

    def get_element_text(self, element):
        '''return the text of the element.'''
        if element is not None:
            return element.text
        else:
            print('the element is None!')

    def get_element_children(self, element):
        '''return the element children if the element is not None.'''
        if element is not None:

            return [c for c in element]
        else:
            print('the element is None!')

    def get_elements_tag(self, elements):
        '''return the list of tags of element's tag'''
        if elements is not None:
            tags = []
            for e in elements:
                tags.append(e.tag)
            return tags
        else:
            print('the elements is None!')

    def get_elements_attrib(self, elements):
        '''return the list of attribs of element's attrib'''
        if elements is not None:
            attribs = []
            for a in elements:
                attribs.append(a.attrib)
            return attribs
        else:
            print('the elements is None!')

    def get_elements_text(self, elements):
        '''return the dict of element'''
        if elements is not None:
            text = []
            for t in elements:
                text.append(t.text)
            return dict(zip(self.get_elements_tag(elements), text))
        else:
            print('the elements is None!')

    def main(self, xml):
        # root
        root = self.get_root(xml)

        # children
        children = self.get_element_children(root)

        children_tags = self.get_elements_tag(children)

        children_attribs = self.get_elements_attrib(children)

        i = 0

        # 获取二级元素的每一个子节点的名称和值
        for c in children:
            p = 0
            c_children = self.get_element_children(c)
            dict_text = self.get_elements_text(c_children)
            if dict_text:
                # print (children_tags[i])
                if children_tags[i] == 'TemplateSMS':
                    self.a['templateSMS'] = dict_text
                else:
                    if children_tags[i] == 'SubAccount':
                        k = 0

                        for x in children:
                            if children_tags[k] == 'totalCount':
                                self.m.append(dict_text)
                                self.a['SubAccount'] = self.m
                                p = 1
                            k = k + 1
                        if p == 0:
                            self.a[children_tags[i]] = dict_text
                    else:
                        self.a[children_tags[i]] = dict_text


            else:
                self.a[children_tags[i]] = c.text
            i = i + 1
        return self.a

    def main2(self, xml):
        # root
        root = self.get_root(xml)

        # children
        children = self.get_element_children(root)

        children_tags = self.get_elements_tag(children)

        children_attribs = self.get_elements_attrib(children)

        i = 0

        # 获取二级元素的每一个子节点的名称和值
        for c in children:
            p = 0
            c_children = self.get_element_children(c)
            dict_text = self.get_elements_text(c_children)
            if dict_text:
                if children_tags[i] == 'TemplateSMS':
                    k = 0

                    for x in children:
                        if children_tags[k] == 'totalCount':
                            self.m.append(dict_text)
                            self.a['TemplateSMS'] = self.m
                            p = 1
                        k = k + 1
                    if p == 0:
                        self.a[children_tags[i]] = dict_text
                else:
                    self.a[children_tags[i]] = dict_text

            else:
                self.a[children_tags[i]] = c.text
            i = i + 1
        return self.a

CCPRestSDK.py

# -*- coding: UTF-8 -*-
#  Copyright (c) 2014 The CCP project authors. All Rights Reserved.
#
#  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
#  that can be found in the LICENSE file in the root of the web site.
#
#   http://www.yuntongxun.com
#
#  An additional intellectual property rights grant can be found
#  in the file PATENTS.  All contributing project authors may
#  be found in the AUTHORS file in the root of the source tree.

import base64
import datetime
import json
from hashlib import md5
from urllib import request as urllib2

from .xmltojson import xmltojson


class REST:
    AccountSid = ''
    AccountToken = ''
    AppId = ''
    SubAccountSid = ''
    SubAccountToken = ''
    ServerIP = ''
    ServerPort = ''
    SoftVersion = ''
    Iflog = False  # 是否打印日志
    Batch = ''  # 时间戳
    BodyType = 'xml'  # 包体格式,可填值:json 、xml

    # 初始化
    # @param serverIP       必选参数    服务器地址
    # @param serverPort     必选参数    服务器端口
    # @param softVersion    必选参数    REST版本号
    def __init__(self, ServerIP, ServerPort, SoftVersion):

        self.ServerIP = ServerIP
        self.ServerPort = ServerPort
        self.SoftVersion = SoftVersion

    # 设置主帐号
    # @param AccountSid  必选参数    主帐号
    # @param AccountToken  必选参数    主帐号Token

    def setAccount(self, AccountSid, AccountToken):
        self.AccountSid = AccountSid
        self.AccountToken = AccountToken

    # 设置子帐号
    # 
    # @param SubAccountSid  必选参数    子帐号
    # @param SubAccountToken  必选参数    子帐号Token

    def setSubAccount(self, SubAccountSid, SubAccountToken):
        self.SubAccountSid = SubAccountSid
        self.SubAccountToken = SubAccountToken

    # 设置应用ID
    # 
    # @param AppId  必选参数    应用ID

    def setAppId(self, AppId):
        self.AppId = AppId

    def log(self, url, body, data):
        print('这是请求的URL:')
        print(url)
        print('这是请求包体:')
        print(body)
        print('这是响应包体:')
        print(data)
        print('********************************')

    # 创建子账号
    # @param friendlyName   必选参数      子帐号名称
    def CreateSubAccount(self, friendlyName):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/SubAccounts?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        req.add_header("Authorization", auth)
        # xml格式
        body = '''<?xml version="1.0" encoding="utf-8"?><SubAccount><appId>%s</appId>\
            <friendlyName>%s</friendlyName>\
            </SubAccount>\
            ''' % (self.AppId, friendlyName)

        if self.BodyType == 'json':
            # json格式
            body = '''{"friendlyName": "%s", "appId": "%s"}''' % (friendlyName, self.AppId)
        data = ''
        req.data 
  • 9
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Python发送短信是一种快捷高效的方式,通过API可以将短信快速、高效地发送到目标手机上。Python作为一种高效的编程语言,可以通过各种方式发送短信,如使用短信平台API、SMTP邮件方式、串口方式等等。在开始使用Python发送短信之前,需要满足一些要求,包括Python 3.x版本、电话号码或短信服务的网站访问凭据等。若使用Twilio发送短信,也需要相应的凭据。总体来说,Python发送短信是一种值得推广和应用的方式。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [chatgpt赋能pythonPython发送短信:快捷而高效的短信发送方式](https://blog.csdn.net/tulingtest/article/details/130878788)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [chatgpt赋能python:用Python发送短信的简单方法](https://blog.csdn.net/u012804784/article/details/130908472)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值