Python自动发送邮件:详细教程与示例代码
在Python中,可以使用smtplib
和email
库来自动发送邮件。以下是一个简单的例子,演示如何使用Python发送邮件。
首先,你需要确保你的邮箱开启了SMTP服务,并获取到了相应的服务器地址、端口、用户名和密码。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 邮件发送者和接收者
sender_email = "your_email@example.com"
receiver_email = "receiver_email@example.com"
# 创建邮件对象和设置邮件内容
message = MIMEMultipart("alternative")
message["Subject"] = "Python Email Test"
message["From"] = sender_email
message["To"] = receiver_email
# 创建邮件正文
text = """\
This is an example email
"""
html = """\
<html>
<body>
<p>This is an example email</p>
</body>
</html>
"""
# 添加正文到邮件对象
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# 添加正文到邮件消息
message.attach(part1)
message.attach(part2)
# 发送邮件服务器配置
email_password = "your_email_password"
email_server = "smtp.example.com"
email_port = 587 # 或者你使用的端口号
# 发送邮件
try:
# 创建SMTP服务器连接
server = smtplib.SMTP(email_server, email_port)
server.ehlo() # 与服务器通信
server.starttls() # 启用TLS
server.login(sender_email, email_password)
# 发送邮件
server.sendmail(sender_email, receiver_email, message.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Something went wrong: {e}")
finally:
server.quit()
确保替换your_email@example.com
, receiver_email@example.com
, your_email_password
, smtp.example.com
, 和email_port
为你自己的邮箱信息和SMTP服务器信息。
运行这段代码,你的邮箱将会收到一封来自你自己账号的测试邮件。确保你的邮箱和密码是正确的,并且SMTP服务是开启的,否则你会收到一个错误信息。
评论已关闭