参考资料
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, FolderCollection
credentials = 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, Message
some_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 os
from config import cfg
credentials = 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 work
user='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 string
from 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.path
config = 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()