在Python中,我们可以使用内置的smtplib和poplib库,或者使用更高级的库,如yagmail,来自动化收发邮件。下面,我将提供一个使用smtplib和poplib的示例。
由于它们是Python的内置库,你无需通过pip进行安装。
发送邮件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 设置SMTP服务器和端口
smtp_server = "smtp.example.com"
port = 587 # 或465
# 设置发件人和收件人的邮箱地址
sender_email = "your-email@example.com"
receiver_email = "receiver-email@example.com"
password = "your-password"
# 创建一个MIMEMultipart对象并设置其内容
message = MIMEMultipart("alternative")
message["Subject"] = "Hello there"
message["From"] = sender_email
message["To"] = receiver_email
# 创建邮件正文
text = """\
Hello,
This is a test email.
"""
part1 = MIMEText(text, "plain")
message.attach(part1)
# 连接到SMTP服务器,发送邮件
with smtplib.SMTP(smtp_server, port) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
接收邮件
import poplib
import email
from email import header
from email.parser import BytesParser
# 设置POP3服务器和端口
pop_server = "pop.example.com"
port = 995 # 或110
# 连接到POP3服务器,下载邮件
with poplib.POP3_SSL(pop_server, port) as server:
server.user("your-email@example.com")
server.pass_("your-password")
messages = [message for message in server.list()[1] if message[0].decode("utf-8") != b"."]
for message in messages:
response, mail = server.retr(message[0])
parser = BytesParser(mail)
for part in parser.parse():
if part.get_content_type() == "text/plain": # 如果邮件正文是纯文本
body = part.get_payload(decode=True) # 获取邮件正文内容并解码
print(body.decode("utf-8")) # 打印邮件正文内容
注意:这些示例代码中的服务器地址、端口、邮箱地址和密码都需要你替换为你自己的信息。