import smtplib
from email.mime.text import MIMEText
from email.header import Header
import poplib
# 邮箱账号和授权码
email = "您的QQ邮箱账号"
password = "您的QQ邮箱授权码,要在邮箱设置里获取"
# 邮箱SMTP服务器
smtp_server = "smtp.qq.com"
# 邮箱POP3服务器
pop_server = "pop.qq.com"
# 邮件主题和内容
subject = "Python测试邮件"
content = "这是一封Python测试邮件"
# 创建邮件对象
message = MIMEText(content, 'plain', 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
message['From'] = email
message['To'] = "收件人QQ邮箱地址"
# 登录SMTP服务器并发送邮件
try:
server = smtplib.SMTP(smtp_server)
server.login(email, password)
server.sendmail(email, message['To'], message.as_string())
print("邮件发送成功")
except smtplib.SMTPException as e:
print("邮件发送失败:", e)
finally:
server.quit()
# 登录POP3服务器并获取邮件内容
try:
server = poplib.POP3(pop_server)
server.user(email)
server.pass_(password)
response, data = server.stat()
count = int(data[1])
message_ids = [str(i[0]) for i in data[2]]
messages = []
for i in range(0, count):
line = server.retr(i+1)[0]
body = line.decode('utf-8')
messages.append({'message_id': message_ids[i], 'body': body})
print("获取到{}封邮件,以下是部分邮件内容:".format(count))
for i, message in enumerate(messages):
print("{}. {}:{}".format(i+1, message_ids[i], message['body']))
except poplib.error_proto as e:
print("POP3服务器连接失败:", e)
finally:
server.quit()