库函数的导入,其中getpass是防止信息泄露
import poplib,email,datetime,time,traceback,sys,telnetlib,zipfile,os,shutil
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
from getpass import getpass
采用面向对象的方式进行编写代码,我们先定义一个邮件管理类,传入参数包括邮箱服务器地址(默认qq邮箱,因为我个人用的foxmail.com,和qq邮箱进行了绑定),默认保存地址代码保存地址。当实例化这个类时,自动调用init这个函数,调用函数需要用户输入邮箱用户名和密码,其中密码是需要获取的邮箱授权码。
class EmailManager(object):
'''默认为qq邮箱,保存路径为代码源文件'''
def __init__(self, pop3_server='pop.qq.com', save_path=os.getcwd()):
self.__email_user = getpass('邮箱用户名:') #定义私有属性,别人无法访问
self.__password = getpass('邮箱密码') #定义私有属性,别人无法访问
self.pop3_server = pop3_server
self.save_path = save_path
#登录检查
try:
telnetlib.Telnet('pop.qq.com',995) #采用995端口
server=poplib.POP3_SSL(self.pop3_server,995,timeout=10)
#self.server=poplib.POP3(pop3_server,110,timeout=10) #有些邮箱系统需要用下面的port
server.user(self.__email_user)
server.pass_(self.__password)
# 返回邮件数量和占用空间:
print('Login success!The number of the messages is: %s.The occupied space is: %s'%server.stat())
# list()返回所有邮件的编号:
resp,mails,octets = server.list()
except Exception as e:
print('请仔细检查账户和密码!')
定义字符串编码转换函数
#定义字符编码转换函数
def decode_str(self,str_in):
value, charset = decode_header(str_in)[0]
if charset:
value = value.decode(charset)
return value
定义邮件下载函数
#附件下载函数
def save_att_file(self,save_path,msg):
for part in msg.walk():
file_name = part.get_filename()
# contentType = part.get_content_type()
attachment_files =[]
if file_name:
file_name = self.decode_str(file_name)
data = part.get_payload(decode=True)
att_file = open(os.path.join(save_path,file_name), 'wb')
attachment_files.append(file_name)
att_file.write(data)
att_file.close()
print(f"附件 {file_name} 下载完成")
下载指定的附件
#下载指定条件的附件
def Download_att_file(self,Condition=True):
'''Condition代表下载条件:
例:("毕业论文" in Subject)&(date2 == '2023-03-23')
'''
server,mails = self.login()
for i in range(1,len(mails)+1):
resp,lines,octets = server.retr(i)
msg_content=b'\r\n'.join(lines).decode()
# 解析邮件:
msg = Parser().parsestr(msg_content)
From = parseaddr(msg.get('from'))[1] #发件人
To = parseaddr(msg.get('To'))[1] #收件人
Cc = parseaddr(msg.get_all('Cc'))[1] #抄送人
Subject = self.decode_str(parseaddr(msg.get('Subject'))[1]) #主题
# 获取邮件时间,格式化收件时间
date1 = time.strptime(msg.get("Date")[0:24],'%a, %d %b %Y %H:%M:%S')
# 邮件时间格式转换
date2 = time.strftime("%Y-%m-%d",date1)
#print(f'发件人:{From};收件人:{To};抄送人:{Cc};主题:{Subject};收件日期:{date2}')
#添加下载附件的条件
if Condition:
self.save_att_file(self.save_path,msg)
运行函数
if __name__ =='__main__':
manager = EmailManager()
manager.Download_att_file()
结果如图:
汇总代码
import poplib,email,datetime,time,traceback,sys,telnetlib,zipfile,os,shutil
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
from getpass import getpass
#定义一个对象类
class EmailManager(object):
'''默认为qq邮箱,保存路径为代码源文件'''
def __init__(self, pop3_server='pop.qq.com', save_path=os.getcwd()):
self.__email_user = getpass('邮箱用户名:') #定义私有属性,别人无法访问
self.__password = getpass('邮箱密码') #定义私有属性,别人无法访问
self.pop3_server = pop3_server
self.save_path = save_path
#登录
try:
telnetlib.Telnet('pop.qq.com',995) #采用995端口
server=poplib.POP3_SSL(self.pop3_server,995,timeout=10)
#self.server=poplib.POP3(pop3_server,110,timeout=10) #有些邮箱系统需要用下面的port
server.user(self.__email_user)
server.pass_(self.__password)
# 返回邮件数量和占用空间:
print('Login success!The number of the messages is: %s.The occupied space is: %s'%server.stat())
# list()返回所有邮件的编号:
resp,mails,octets = server.list()
except Exception as e:
print('请仔细检查账户和密码!密码是授权码非邮箱密码!')
#登录返回mails
def login(self):
telnetlib.Telnet('pop.qq.com',995)
server=poplib.POP3_SSL(self.pop3_server,995,timeout=10)
#self.server=poplib.POP3(pop3_server,110,timeout=10) #有些邮箱系统需要用下面的port
server.user(self.__email_user)
server.pass_(self.__password)
resp,mails,octets = server.list()
return server,mails
#定义字符编码转换函数
def decode_str(self,str_in):
value, charset = decode_header(str_in)[0]
if charset:
value = value.decode(charset)
return value
#附件下载函数
def save_att_file(self,save_path,msg):
for part in msg.walk():
file_name = part.get_filename()
# contentType = part.get_content_type()
attachment_files =[]
if file_name:
file_name = self.decode_str(file_name)
data = part.get_payload(decode=True)
att_file = open(os.path.join(save_path,file_name), 'wb')
attachment_files.append(file_name)
att_file.write(data)
att_file.close()
print(f"附件 {file_name} 下载完成")
#下载指定条件的附件
def Download_att_file(self,Condition=True):
'''Condition代表下载条件:
例:("毕业论文" in Subject)&(date2 == '2023-03-23')
'''
server,mails = self.login()
for i in range(1,len(mails)+1):
resp,lines,octets = server.retr(i)
msg_content=b'\r\n'.join(lines).decode()
# 解析邮件:
msg = Parser().parsestr(msg_content)
From = parseaddr(msg.get('from'))[1] #发件人
To = parseaddr(msg.get('To'))[1] #收件人
Cc = parseaddr(msg.get_all('Cc'))[1] #抄送人
Subject = self.decode_str(parseaddr(msg.get('Subject'))[1]) #主题
# 获取邮件时间,格式化收件时间
date1 = time.strptime(msg.get("Date")[0:24],'%a, %d %b %Y %H:%M:%S')
# 邮件时间格式转换
date2 = time.strftime("%Y-%m-%d",date1)
#print(f'发件人:{From};收件人:{To};抄送人:{Cc};主题:{Subject};收件日期:{date2}')
#添加下载附件的条件
if Condition:
self.save_att_file(self.save_path,msg)
if __name__ =='__main__':
manager = EmailManager()
manager.Download_att_file()