要通过Python给手机发送短信,您可以使用第三方短信服务提供商的API。以下是使用Twilio和PushPlus服务的示例代码:
使用Twilio发送短信
1. 注册Twilio账户并获取账户SID、认证令牌和Twilio号码。
2. 安装`twilio`包:
pip install twilio
3. 发送短信的代码示例:
from twilio.rest import Client替换为你的Twilio账户SID和认证令牌account_sid = 'your_account_sid'auth_token = 'your_auth_token'创建Twilio客户端client = Client(account_sid, auth_token)替换为接收短信的手机号码to_phone_number = '+0'替换为你的Twilio电话号码from_phone_number = '+'发送短信message = client.messages.create(to=to_phone_number,from_=from_phone_number,body='Hello from Python Twilio!')print(message.sid)
使用PushPlus发送短信
1. 访问PushPlus网站,登录并获取个人token。
2. 发送短信的代码示例:
import requestsdef send_notice(content):token = 'your_token' 替换为你的个人tokentitle = '训练成功'url = f'http://www.pushplus.plus/send?token={token}&title={title}&content={content}&template=html'response = requests.get(url)发送短信send_notice('训练结束的通知')
请确保替换示例代码中的占位符,如账户SID、认证令牌、电话号码和个人token,以适应您的实际情况。
您还可以选择其他短信服务提供商,如短信宝、IFTTT等,具体步骤和代码会有所不同,但基本原理相似,都是通过发送HTTP请求到短信服务提供商的API接口来实现短信发送功能

