#!/usr/bin/env python3

# -*- coding: utf-8 -*-

# -*- encoding: gbk -*-

# 目前只测试过网易163邮箱,qq邮箱时间格式与163有所不同需要更改时间格式那部分的代码

import poplib

import email

import datetime

import time

from email.parser import Parser

from email.header import decode_header

from email.utils import parseaddr

import traceback

import sys

import telnetlib

import zipfile

import os

import shutil

# from email.utils import parseaddr

class c_step4_get_email:

"""创建一个处理邮箱附件下载和解压的类"""

# @staticmethod

def decode_str(str_in):

"""字符编码转换"""

value, charset = decode_header(str_in)[0]

if charset:

value = value.decode(charset)

return value

# @staticmethod

def get_att(msg_in, str_day_in):

"""解析邮件,获取附件"""

# import email

attachment_files = []

for part in msg_in.walk():

# 获取附件名称类型

file_name = part.get_filename()

# contType = part.get_content_type()

if file_name:

h = email.header.Header(file_name)

# 对附件名称进行解码

dh = email.header.decode_header(h)

filename = dh[0][0]

if dh[0][1]:

# 将附件名称可读化

filename = c_step4_get_email.decode_str(str(filename, dh[0][1]))

print(filename)

# filename = filename.encode("utf-8")

# 下载附件

data = part.get_payload(decode=True)

# 在指定目录下创建文件,注意二进制文件需要用wb模式打开

att_file = open('C:\\Users\\Administrator\\Desktop\\银联对账zip文件临时存放文件夹' + '\\' + filename, 'wb')

attachment_files.append(filename)

att_file.write(data)  # 保存附件

att_file.close()

return attachment_files

# @staticmethod

def run_ing():

"""登陆邮箱"""

# 输入邮件地址, 口令和POP3服务器地址:

email_user = '******@163.com'

# 此处密码是授权码,用于登录第三方邮件客户端

password = '******'

pop3_server = 'pop.163.com'

# 日期赋值

day = datetime.date.today()

str_day = str(day).replace('-', '')

print(str_day)

# 连接到POP3服务器,有些邮箱服务器需要ssl加密,可以使用poplib.POP3_SSL

try:

telnetlib.Telnet('pop.163.com', 995)

server = poplib.POP3_SSL(pop3_server, 995, timeout=10)

except:

time.sleep(5)

server = poplib.POP3(pop3_server, 110, timeout=10)

# 可以打开或关闭调试信息

server.set_debuglevel(1)

# 打印POP3服务器的欢迎文字:

print(server.getwelcome().decode('utf-8'))

# 身份认证:

server.user(email_user)

server.pass_(password)

# 返回邮件数量和占用空间:

print('Messages: %s. Size: %s' % server.stat())

# list()返回所有邮件的编号:

resp, mails, octets = server.list()

# 可以查看返回的列表类似[b'1 82923', b'2 2184', ...]

print(mails)

index = len(mails)

# 倒序遍历邮件

# for i in range(index, 0, -1):

# 顺序遍历邮件

a = 1

while a == 1:

global number

for i in range(number, index+1):

resp, lines, octets = server.retr(i)

# lines存储了邮件的原始文本的每一行,

# 邮件的原始文本:

msg_content = b'\r\n'.join(lines).decode('unicode_escape')

# 解析邮件:

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 = parseaddr(msg.get('Subject'))[1]        #主题

print('from:%s,to:%s,Cc:%s,Subject%s:'%(From,To,Cc,Subject))

if From == 'operator_gd@unionpay.com':         # 判断是否来自指定邮箱

# 获取邮件时间,格式化收件时间

date1 = time.strptime(msg.get("Date")[0:24], '%a, %d %b %Y %H:%M:%S')

# 邮件时间格式转换

date2 = time.strftime("%Y%m%d", date1)

if date2

# 倒叙用break

# break

# 顺叙用continue

continue

else:

# 获取附件

c_step4_get_email.get_att(msg, str_day)

a += 1

else:

number += 1

# c_step4_get_email.run_ing()

server.quit()

def un_zip(file_name):

"""解压单个文件"""

zip_file = zipfile.ZipFile(file_name)           #读取zip文件

for names in zip_file.namelist():

zip_file.extract(names,local)               #解压

zip_file.close()

if os.path.exists(file_name):                 #用os中rename 重命名的方法剪贴zip文件

os.rename(file_name,zip_path + file_name[48:])

print(file_name,'解压成功')

def un_zip_Tree(path):

"""解压文件夹中的zip文件"""

if not os.path.exists(path):                    # 如果本地文件夹不存在,则创建它

os.makedirs(path)

for file in os.listdir(path):                   #listdir()返回当前目录下清单列表

Local = os.path.join(path, file)             #os.path.join()用于拼接文件路径

if os.path.isdir(file):                      # 判断是否是文件

if not os.path.exists(Local):           #对于文件夹:如果本地不存在,就创建该文件夹

os.makedirs(Local)

un_zip_Tree(path)

else:  # 是文件

if os.path.splitext(Local)[1] == '.zip': #os.path.splitext(Remote)[1]获取文件扩展名,判断是否为.zip文件

c_step4_get_email.un_zip(Local)      #解压文件

if __name__ == '__main__':

origin = sys.stdout

number = 1

zip_path = 'C:\\Users\\Administrator\\Desktop\\'

local = 'C:\\Users\\Administrator\\Desktop\\'         # 此处看实际解压到的存储路径

path = 'C:\\Users\\Administrator\\Desktop\\'          # 此处看实际存储压缩文件的路径

# 简单的日志处理  将日志写入到log.txt

f = open('E:\python_project\log.txt', 'w')

sys.stdout = f

try:

c_step4_get_email.run_ing()

except Exception as e:

s = traceback.format_exc()

print(e)

tra = traceback.print_exc()

sys.stdout = origin

c_step4_get_email.un_zip_Tree(path)

f.close()

python下载邮箱附件_基于Python3 下载邮箱附件,并解压到指定文件夹相关推荐

  1. python解压到指定文件夹_在Python中压缩和解压文件

    Python部落(python.freelycode.com)组织翻译,禁止转载,欢迎转发. 如果你已经使用计算机一段时间,你可能遇到了.zip扩展名的文件.它们是可以保存许多其他文件,文件夹和子文件 ...

  2. python解压到指定文件夹_Python:将文件解压缩到当前工作目录,但不保存zip中的目录结构...

    我有一个像这样的zip文件: myArchive.zip | -folder1 | --folder2 | ---myimage.jpg 当我尝试提取myimage.jpg时: with zipfil ...

  3. node 下载Url上的压缩包 解压并保存文件夹到本地

    npm安装compressing npm install compressing 下载url上的压缩包,指定解压路径,解压文件 const request = require("reques ...

  4. python批量解压批量压缩文件夹(逐个)

    系列文章目录 文章目录 系列文章目录 前言 一.python批量解压 二.python批量压缩 总结 前言 一.python批量解压 提示:如果是重要数据解压前请先备份,解压后会覆盖原压缩文件!! 解 ...

  5. python代码检查工具_基于Python3的漏洞检测工具 ( Python3 插件式框架 )

    [TOC] Python3 漏洞检测工具 -- lance lance, a simple version of the vulnerability detection framework based ...

  6. python爱因斯坦的问题_基于Python3的趣味数学问题

    基于Python3的趣味数学问题 Pro1. 数独(Sudoku)根据九宫格盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行.每一列.每一个宫(3*3)内的数字均含1-9这9个数字. Pro2 ...

  7. python3 zlib 实现压缩与解压字符串与文件数据流

    关于python3 zlib 压缩解压情况总结如下: 字符串:使用zlib.compress方法压缩字符串,使用zlib.decompress方法解压字符串. 数据流:压缩:zlib.compress ...

  8. python日志分析工具_基于Python3的Web日志分析小工具

    PyWebLog 网站日志分析小工具 环境 Python3.5 Mysql 预览 安装 pip install pymysql pip install flask 导入日志 python Log.py ...

  9. python标准库os中用来列出_Python 标准库 os 中用来列出指定文件夹中的文件和子文件夹列表的方式是listdir()。_高职高专数字资源平台答案_学小易找答案...

    [单选题]生物膜主要成分是脂与蛋白质,它们主要是通过什么键相连.( ) (2.0分) [单选题]卵磷脂分子是由甘油.脂酸.磷酸.( )基团组成. (2.0分) [名词解释]活力单位 [单选题]1. 脂 ...

最新文章

  1. 如何用TensorFlow训练词向量
  2. 蓝桥杯审核要多久_商标审核要多久?
  3. [翻译] WPAttributedMarkup
  4. arcgis-shp文件属性表导出为dbf或txt
  5. FlexiBO:基于成本感知的深度神经网络多目标优化
  6. 0009:err:module:__wine_process_init failed to load xxx
  7. python小括号( )与中括号 [ ]
  8. CS224N笔记——Word Window分类与神经网络
  9. canvas绘制经典星空连线效果
  10. Linux设备驱动——驱动模型
  11. 内容云筑底,火山引擎能否为企业添一把火?
  12. 安装Microsoft Office Document Image Writer
  13. SAP-FI-财务报表版本设定
  14. java 当前类相对路径_JAVA文件中获取该项目的相对路径方法
  15. 在英特尔独立显卡上训练ResNet PyTorch模型
  16. react 的 render 函数
  17. 大数据学习路线图,大数据需要学什么
  18. 震惊:七成人对薪资不满,多劳并非能多得
  19. 深度学习入门 | Self-attentionRNNLSTM
  20. 都是学 AI,为什么别人薪资比你高?

热门文章

  1. npm run 脚本背后的事情
  2. env-cmd is not recognized as an internal or external command
  3. SAP Spartacus如何为不同的environment设置不同的baseUrl
  4. HTML span标签学习笔记
  5. Github提交记录里用户超链接无法显示的问题
  6. SAP Spartacus里如何查看HTTP请求的状态
  7. SAP AMDP介绍 - ABAP托管的HANA数据库过程
  8. 如何去除Eclipse Maven插件里关于Managed version的警告消息
  9. sales status change in ERP
  10. how is home button implemented in Fiori launchpad