Python 发送消息:一个全面指南
Python 是一个多功能的编程语言,可以应用于各种各样的任务和项目。其中之一就是发送消息,您可以使用 Python 发送电子邮件、短信、推送通知等消息形式。在本篇文章中,我们将介绍如何使用 Python 发送各种类型的消息。
发送电子邮件
配置SMTP(简单邮件传输协议)
如果您想要使用 Python 发送电子邮件,则需要配置 SMTP 认证。以下是配置 SMTP 的示例代码:
import smtplib
smtp_server = "smtp.gmail.com"
smtp_port = 587
smtp_username = "example@gmail.com"
smtp_password = "example_password"
# 连接SMTP服务器
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
# 登录SMTP服务器
server.login(smtp_username, smtp_password)
# 发送电子邮件
from_email = "example@gmail.com"
to_email = "recipient@example.com"
subject = "Test email from Python"
body = "This is a test email sent using Python."
message = f"From: {from_email}\nTo: {to_email}\nSubject: {subject}\n\n{body}