随着电子邮件在我们生活和工作中的广泛应用,通过Python编写程序来实现邮件的发送和接收成为一项有趣而实用的技能。在这篇博客中,我们将详细介绍如何使用Python中的smtplib
模块发送邮件,以及使用poplib
模块收取邮件。
1. SMTP发送邮件
首先,我们将介绍如何使用SMTP协议发送邮件。以下是一个简单的Python脚本,演示了如何通过SMTP服务器发送邮件。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 发送者邮箱
sender_email = "your_email@gmail.com"
# 发送者邮箱密码
sender_password = "your_email_password"
# 接收者邮箱
receiver_email = "recipient_email@gmail.com"
# 构建邮件内容
subject = "Python SMTP邮件"
body = "这是一封通过Python发送的邮件。"
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
# 连接到SMTP服务器
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
# 登录邮箱
server.login(sender_email, sender_password)
# 发送邮件
server.sendmail(sender_email, receiver_email, message.as_string())
print("邮件发送成功!")
请注意:
- 请将
your_email@gmail.com
、your_email_password
和recipient_email@gmail.com
替换为你的发件人邮箱、密码和收件人邮箱。 - 如果你使用的是Gmail,SMTP服务器是
smtp.gmail.com
,端口是587
。
2. POP3收取邮件
接下来,我们将介绍如何使用POP3协议收取邮件。以下是一个简单的Python脚本,演示了如何通过POP3服务器接收邮件。
import poplib
from email.parser import Parser
# 收件人邮箱
receiver_email = "your_email@gmail.com"
# 收件人邮箱密码
receiver_password = "your_email_password"
# 连接到POP3服务器
with poplib.POP3_SSL("pop.gmail.com", 995) as server:
# 登录邮箱
server.user(receiver_email)
server.pass_(receiver_password)
# 获取邮箱状态
status = server.stat()
print(f"共有 {status[0]} 封邮件,占用空间 {status[1]} 字节")
# 获取最新一封邮件
_, messages, _ = server.list()
if messages:
latest_email_index = int(messages[-1].split()[0])
_, lines, _ = server.retr(latest_email_index)
email_content = b"\n".join(lines).decode("utf-8")
# 解析邮件内容
email_parser = Parser()
email_message = email_parser.parsestr(email_content)
print(f"发件人:{email_message.get('From')}")
print(f"主题:{email_message.get('Subject')}")
print(f"正文:{email_message.get_payload()}")
请注意:
- 请将
your_email@gmail.com
和your_email_password
替换为你的收件人邮箱和密码。 - 如果你使用的是Gmail,POP3服务器是
pop.gmail.com
,端口是995
。
通过这两个例子,你可以看到如何使用Python中的SMTP和POP3模块实现邮件的发送和接收。这是一个有趣且实用的应用,特别是当你需要在程序中实现自动发送和接收邮件的功能时。希望这个博客对你理解邮件的发送和接收过程以及如何在Python中实现这些功能有所帮助。