Skip to content

Instantly share code, notes, and snippets.

@dhruvilp
Last active July 22, 2022 22:16
Show Gist options
  • Save dhruvilp/43e6aa3125a9b56a342eb04c1afe40d3 to your computer and use it in GitHub Desktop.
Save dhruvilp/43e6aa3125a9b56a342eb04c1afe40d3 to your computer and use it in GitHub Desktop.
retrieving-attachments-from-exchange-mailbox-using-python
# source: https://www.moh10ly.com/retrieving-attachments-from-exchange-mailbox-using-python/
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='PWD')
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment