[Python案例] 发送短信

Posted by Chase Shen on 2022-04-13
Estimated Reading Time 1 Minutes
Words 378 In Total
Viewed Times

发送短信是项目中常见的功能,网站的注册码、验证码、营销信息基本上都是通过短信来发送给用户的。在下面的代码中我们使用了互亿无线短信平台提供的API接口实现了发送短信的服务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import urllib.parse
import http.client
import json

def main():
host = "106.ihuyi.com"
sms_send_uri = '/webservice/sms.php?method=Submit'
params = urllib.parse.urlencode({'account': '你自己的账号', 'password': '你自己的密码', 'content': '您的验证码是:147258。请不要把验证码泄露给其他人。', 'mobile': '接收者的手机号', 'format': 'json'})
headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}
conn = http.client.HTTPConnection(host, port=80, timeout=30)
try:
conn.request('POST', sms_send_uri, params, headers)
response = conn.getresponse()
response_str = response.read()
jsonstr = response_str.decode('utf-8')
print(json.loads(jsonstr))
except Exception as e:
print(f'Failed to send sms: {e}')
finally:
conn.close()


if __name__ == '__main__':
main()

许多短信服务提供商都有对应的Python库,用于与其API进行交互。你可以安装相应的库,并按照其文档中的说明使用。
以下是一个使用Twilio发送短信的示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from twilio.rest import Client

# Your Twilio Account SID and Auth Token
account_sid = 'your_account_sid'
auth_token = 'your_auth_token'

# Initialize Twilio Client
client = Client(account_sid, auth_token)

# Send SMS
message = client.messages.create(
body='Hello, this is a test message from Twilio!',
from_='+1234567890', # Your Twilio phone number
to='+9876543210' # Recipient's phone number
)

print('Message SID:', message.sid)

如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !