python

怎么使用Python代码实现自动发送短信

小亿
124
2024-03-01 19:47:17
栏目: 编程语言

要使用Python实现自动发送短信,你可以使用第三方的短信服务提供商的API。其中,Twilio是一个常用的短信服务提供商。以下是一个使用Twilio API发送短信的示例代码:

  1. 首先,在Twilio官网注册账号,并创建一个项目,获取账号SID和认证令牌。

  2. 安装Twilio库:

pip install twilio
  1. 编写Python代码:
from twilio.rest import Client

# Your Twilio account SID and auth token
account_sid = 'YOUR_ACCOUNT_SID'
auth_token = 'YOUR_AUTH_TOKEN'

# Your Twilio phone number
from_number = 'YOUR_TWILIO_PHONE_NUMBER'

# Recipient's phone number
to_number = '+1234567890'

# Message to be sent
message = 'Hello, this is a test message from Twilio!'

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

# Send message
message = client.messages.create(
    body=message,
    from_=from_number,
    to=to_number
)

print('Message sent successfully!')

将上述代码中的YOUR_ACCOUNT_SIDYOUR_AUTH_TOKENYOUR_TWILIO_PHONE_NUMBER替换为你在Twilio官网获取的信息。然后运行代码,即可发送短信。

0
看了该问题的人还看了