1.发送邮件
#coding=utf-8
import smtplib
from email.mime.text import MIMEText
#第三方SMTP服务
mail_host = "smtp.qq.com"
mail_user = "邮箱账号"
mail_pass = "是授权码而不是密码"
sender = "xxx@qq.com"
#receivers = ["xxxx@qq.com","xxxxxx@qq.com"]
message = MIMEText("Python邮件发送测试","plain","utf-8")
message["From"] = sender
message["To"] = ";".join(receivers)
message["Subject"] = "Python邮件发送测试"
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host,25)
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender,receivers,message.as_string())
print("发送成功")
except smtplib.SMTPException as e:
print(f"发送失败,错误原因:{e}")
2.接收邮件
#coding=utf-8
import poplib
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
#输入电子邮件,口令,邮件服务器地址
email = "xxx@qq.com"
password = "登陆口令"
pop3_server = "pop.qq.com"
#链接pop3服务器,并已开启ssl
server = poplib.POP3_SSL(pop3_server)
#打开或关闭调式信息
server.set_debuglevel(1)
#打印pop3服务器的欢迎文字
print(server.getWelcome().decode("utf-8"))
#身份认证
server.user(email)
server.pass_(password)
#返回邮件数量和占用空间
print("邮件数量:%s封,大小:%.2fMB" % (server.stat()[0],server.stat()[1] / 1024 / 1024))
#list()返回所有邮件编号
resp,mails,octets = server.list()
#获取最新一封邮件,索引从1开始
index = len(mails)
resp,lines,octets = server.retr(index)
msg_content = b"\r\n".join(lines).decode("utf-8")
#稍后解析出邮件
msg = Parser().parsestr(msg_content)
def decode_str(s):
value,charset = decode_header(s)[0]
if charset:
value = value.decode(charset)
return value
print("解析获取到的邮件内容如下:\n----------begin-------------")
#打印发件人信息
print(
f"{decode_str(parseaddr(msg.get('From',''))[0])}<{decode_str(parseaddr(msg.get('From',''))[1])}>"
)
#打印收件人信息
print(
f"{decode_str(parseaddr(msg.get('To',''))[0])}<{decode_str(parseaddr(msg.get('To',''))[1])}>"
)
#打印主题信息
print(decode_str(msg["Subject"]))
#打印第一条正文信息
part0 = msg.get_payload()[0]
#解析正文
content = part0.get_payload(decode=True)
print(content.decode(part0.get_content_charset()))
print("-------end----------")
#可以根据邮件索引删除邮件
@server.dele(index)
#关闭连接
server.quit()
「 文章如果对你有帮助,请点个赞哦^^ 」 
0
若无特殊注明,文章均为本站原创或整理发布。
转载请注明本文地址:https://om.fangxiaoxiong.com/2556.html