Dr. Xiao-Le Deng

twilio: Python发送短信

2020-09-23 12:00
#Python

1. 安装和配置twilio

安装:

pip install twilio

https://www.twilio.com/注册并获取账户的ACCOUNT SID、AUTH TOKEN和TRIAL NUMBER信息。

2. Python代码实现过程

1.使用api激活

# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'AC43f87995795328087d57558addfd0078'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

new_key = client.new_keys.create()

print(new_key.sid)

2.将以下代码保存为:text2phone.py

#!/usr/local/bin/python3 
# -*- coding: utf-8 -*-  
"""
Date: 2019/08/31
Author: Xiao-Le Deng
Email: xiaoledeng at gmail.com
text2phone.py - Defines the text2phone() function 
that texts a message to a phone number, revised from Sweigart (2015)
"""

# Preset values:
accountSID = 'AC**********************************' # my ACCOUNT SID
authToken  = '*************************************' # my AUTH TOKEN
myNumber = '*************' # my phone number (e.g., +86....)
twilioNumber = '**************' # my TRIAL NUMBER

from twilio.rest import Client

def text2phone(message):
    twilioClient = Client(accountSID, authToken)
    twilioClient.messages.create(body=message, from_=twilioNumber, to=myNumber)

在同路径下的Python命令行下输入:

import text2phone

text2phone.text2phone('The boring task is finished! Well done!!')

手机会收到以上短信提醒。

3.参考资料