Python Download Exchange E-mail Attachment

  • 参考资料
  • 代码
    • 1
    • 2
      • 考虑时间
    • 3
    • 4

参考资料

https://towardsdatascience.com/download-email-attachment-from-microsoft-exchange-web-services-automatically-9e20770f90ea

https://www.moh10ly.com/retrieving-attachments-from-exchange-mailbox-using-python/

https://stackoverflow.com/questions/43491673/read-emails-and-download-attachment-from-microsoft-exchange-server/45438174#45438174

https://blog.csdn.net/diyiday/article/details/81504363

exchangelib手册 https://ecederstrand.github.io/exchangelib/

代码

1

from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, EWSDateTime, EWSTimeZone, Configuration, NTLM, GSSAPI, CalendarItem, Message, Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, HTMLBody, Build, Version, FolderCollectioncredentials = Credentials(username='moh10ly\info', password='Bc12345$')ews_url = 'https://mail.moh10ly.com/EWS/exchange.asmx'
ews_auth_type = 'NTLM'
primary_smtp_address = 'info@moh10ly.com'
config = Configuration(service_endpoint=ews_url, credentials=credentials, auth_type=ews_auth_type)account = Account(
primary_smtp_address=primary_smtp_address,
config=config, autodiscover=False,
access_type=DELEGATE)import os.path
from exchangelib import Account, FileAttachment, ItemAttachment, Messagesome_folder = account.inbox
for item in some_folder.all():
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
local_path = os.path.join('/temp', attachment.name)
with open(local_path, 'wb') as f:
f.write(attachment.content)#To download all attachments in the inbox:for item in account.inbox.all():
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
local_path = os.path.join('/sky', attachment.name)
with open(local_path, 'wb') as f, attachment.fp as fp:
buffer = fp.read(1024)
while buffer:
f.write(buffer)
buffer = fp.read(1024)
print('Saved attachment to', local_path)

2

from exchangelib import ServiceAccount, Configuration, Account, DELEGATE
import osfrom config import cfgcredentials = ServiceAccount(username=cfg['imap_user'],
password=cfg['imap_password'])config = Configuration(server=cfg['imap_server'], credentials=credentials)
account = Account(primary_smtp_address=cfg['smtp_address'], config=config,
autodiscover=False, access_type=DELEGATE)unread = account.inbox.filter() # returns all mails
for msg in unread:
print(msg)
print("attachments ={}".format(msg.attachments))
print("conversation_id ={}".format(msg.conversation_id))
print("last_modified_time={}".format(msg.last_modified_time))
print("datetime_sent ={}".format(msg.datetime_sent))
print("sender ={}".format(msg.sender))
print("text_body={}".format(msg.text_body.encode('UTF-8')))
print("#" * 80)
for attachment in msg.attachments:
fpath = os.path.join(cfg['download_folder'], attachment.name)
with open(fpath, 'wb') as f:
f.write(attachment.content)

考虑时间

The following code logins to the FTP server (ftp.login()), navigate the target folder (ftp.cwd()) and list all files (ftp.nlst()) that matched the specified prefix (file.startswith())from ftplib import FTP
ftp_server_ip = FTP_SERVER_IP
username = 'username'
password = 'password'
remote_path = 'remote_path'
local_path = 'local_path'
with FTP(ftp_server_ip) as ftp:
ftp.login(user=username, passwd=password)
ftp.cwd(remote_path + '/copied data')
filelist = [file for file in ftp.nlst() if file.startswith('YOUR_FILE_PREFIX')]
After downloading the attachments locally, I upload the files to the FTP server. I use storbinary to send STOR command to upload the attachments.if attachment.name not in filelist:
# Check if the attachment downloaded before
local_path = os.path.join(local_path, attachment.name)
with open(local_path, 'wb') as f:
f.write(attachment.content)
with FTP(ftp_server_ip) as ftp:
ftp.login(user=username, passwd=password)
ftp.cwd(remote_path)
file = open(local_path, 'rb')
ftp.storbinary('STOR {}'.format(attachment.name), file)
file.close()

3

# this is a script that connects to Exchange to grab mail attachments
# written by MC 30.01.2017 during my time with Nokia - dub2sauce[at]gmail[dot]com
# make sure you have @on.nokia.com domain, otherwise it won't workuser='someone@somewhere.com'
password='topsecret'
SaveLocation = 'C:/Users/admin/Downloads/dist/exchangelib-1.7.6/test/' # where you want the file(s) saved
SubjectSearch = 'FIR'; # it will search all emails containing this stringfrom exchangelib.configuration import Configuration
from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, EWSDateTime, EWSTimeZone, Configuration, NTLM, CalendarItem, Q
from exchangelib.folders import Folder
import logging,os.pathconfig = Configuration(
server='x.x.x.x',
credentials = Credentials(
username=user,
password=password),
verify_ssl=False
)account = Account(
primary_smtp_address='mailbox@company.com',
autodiscover=False,
config=config,
access_type=DELEGATE)for item in account.inbox.all():
if SubjectSearch in item.subject:
for attachment in item.attachments:
local_path = os.path.join(SaveLocation, attachment.name)
with open(local_path, 'wb') as f:
f.write(attachment.content)
print('Saved attachment to', local_path)

4

#-*- encoding: utf-8 -*-
import sys
import locale
import poplib
from email import parser
import email
import string# 确定运行环境的encoding
__g_codeset = sys.getdefaultencoding()
if "ascii"==__g_codeset:
__g_codeset = locale.getdefaultlocale()[1]
#def object2double(obj):
if(obj==None or obj==""):
return 0
else:
return float(obj)
#end if
#def utf8_to_mbs(s):
return s.decode("utf-8").encode(__g_codeset)
#def mbs_to_utf8(s):
return s.decode(__g_codeset).encode("utf-8")
#host = 'pop.exmail.qq.com'
username = 'user1@xxxx.cn'
password = 'password'pop_conn = poplib.POP3_SSL(host)
pop_conn.user(username)
pop_conn.pass_(password)#Get messages from server:
# 获得邮件
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
#print messages#print "--------------------------------------------------"
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#print messages#Parse message intom an email object:
# 分析
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
i = 0
for index in range(0,len(messages)):
message = messages[index];
i = i + 1;
subject = message.get('subject')
h = email.Header.Header(subject)
dh = email.Header.decode_header(h)
subject = unicode(dh[0][0], dh[0][1]).encode('utf8')
mailName = "mail%d.%s" % (i, subject)
f = open('%d.log'%(i), 'w');
print >> f, "Date: ", message["Date"]
print >> f, "From: ", email.utils.parseaddr(message.get('from'))[1]
print >> f, "To: ", email.utils.parseaddr(message.get('to'))[1]
print >> f, "Subject: ", subject
print >> f, "Data: "
j = 0
for part in message.walk():
j = j + 1
fileName = part.get_filename()
contentType = part.get_content_type()
mycode=part.get_content_charset();
# 保存附件
if fileName:
data = part.get_payload(decode=True)
h = email.Header.Header(fileName)
dh = email.Header.decode_header(h)
fname = dh[0][0]
encodeStr = dh[0][1]
if encodeStr != None:
fname = fname.decode(encodeStr, mycode)
#end if
fEx = open("%s"%(fname), 'wb')
fEx.write(data)
fEx.close()
elif contentType == 'text/plain':# or contentType == 'text/html':
#保存正文
data = part.get_payload(decode=True)
content=str(data);
if mycode=='gb2312':
content= mbs_to_utf8(content)
#end if
nPos = content.find('降息')
print("nPos is %d"%(nPos))
print >> f, data
#end if
#end for
f.close()
#end for
pop_conn.quit()

资料仓库——Python Download Exchange E-mail Attachment相关推荐

  1. 资料分享 | python机器学习教程分享来袭

    小天从大学开始,便开启资料收集功能.近几年以AlphaGo为契机,人工智能进入新的发展阶段,再加上日常的深入研究,小天收集整理了丰富的机器学习资料,内容涵盖"机器学习视频",&qu ...

  2. python中exchange函数使用_python基于exchange函数发送邮件过程详解

    python基于exchange函数发送邮件过程详解 作者: shuzihua 更新时间:2020-11-06 10:40:35 原文链接 1.Python hasattr() 函数 描述 hasat ...

  3. 文本备份云仓库-python实用脚本下载

    前言 everbox是一个将evernote作为文件沙盒的接口集合,利用evernote作为文本的存储仓库,方便地对文本文件进行管理. 用法 usage: everbox.py [-h] {init, ...

  4. python资料免费-python 资料

    广告关闭 腾讯云双11爆品提前享,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高满返5000元! github,是源码学习.版本控制不可缺少的网站,找源码学习请第一时间到此网站,f ...

  5. python资料下载-Python大量学习资料集锦(全部免费下载)

    大量Python学习资料集锦: 1. 数据结构:Python语言描述(英).pdf:https://474b.com/file/15153148-463101632 2. 草根学习Python.pdf ...

  6. 【图像处理基础知识】中文车牌识别API-HyperLPR的应用与相关学习资料(python版)

    课题用到了车牌识别,因为C++不会,听说上手比较困难,干脆用了Python做一个原型,编程实现比较快.但是,问题来了,图像处理方面C++是完美工具,大多API.资料都是C++编写的,python的真的 ...

  7. python资料-100G Python从入门到精通全套资料!

    Python 究竟有多火?目前在编程语言排行榜中,Python当之无愧的成为了第一!Python已经逐渐成为所有IT技术的首选语言.几乎所有IT领域都将Python作为首选编程语言. Python崇尚 ...

  8. 现代控制理论(机器人或人工智能方向)补充资料:Python Control Systems Library + Modern Robotics

    现代控制理论广泛应用于智能驾驶和机器人领域,可自行检索资料学习. 在进行研究探索学习时,推荐如下一些资料. 除了掌握Matlab/C++/Java之外,学习一下Python也是不错的选择. Pytho ...

  9. 不用下载券也能下载百度文库资料,Python帮你轻松搞定

    阅读文本大概需要5分钟. 大家可能平时都有在百度文库下载文档的经历,费尽心思好不容易在文库找了一份可以用的资料,一看需要用下载券下载,搞的人很烦. 有的人为了节省时间,就任性办理了个文库VIP,再也不 ...

最新文章

  1. Hadoop葵花宝典(一)
  2. AI一分钟 | 英伟达发布Tesla T4 GPU新品;腾讯发布《2018 年全球自动驾驶法律政策研究报告》...
  3. Docker火遍全球!Docker(Inc)这家公司却要死了???
  4. thymeleaf 使用页面报错_异常处理-SpringBoot中thymeleaf对应前台页面大于号\小于号使用问题...
  5. js中的attribute详解
  6. JAXB –不需要注释
  7. WCF的优势和性能测试
  8. STM32F103mini教程学习总结与心得(四)---->看门狗
  9. 逻辑回归案例模板——信用卡欺诈检测
  10. Unity3D实战【一】Create Project 创建项目导入素材
  11. 一个高速公路交警的救命忠告
  12. 一文了解驱动程序及更新方法
  13. 知识图谱:R2RDF转换之D2RQ
  14. tensor 增加维度_tensor 维度变换
  15. Springboot毕设项目电子竞技赛事管理系统f1v55java+VUE+Mybatis+Maven+Mysql+sprnig)
  16. 消化系统疾病病人的护理题库
  17. Unity3D 编辑器扩展 跳转显示指定目录
  18. 史上最简单笔记本选购攻略(给对笔记本配置完全不懂的小白,建议收藏)
  19. 内核解惑:zw函数和nt函数的区别
  20. 医药企业引进APS系统的效益

热门文章

  1. android 反编译方法、工具介绍
  2. 爬取千库网ppt_python爬取千库网
  3. Thinkphp最新打shang观看视频平台网站源码
  4. Oracle常用函数大全
  5. java-web 常见的缓存技术
  6. 【数理统计】高等代数
  7. Google原生机pixel 刷机Root
  8. while(1);的作用
  9. web前端技术体系大全
  10. MVE-Ubuntu手工打造的三维重建软件(依赖很少的第三方库)