I am currently working on automation solution with Python to read an incoming Outlook emails and download any attachments. I am using exchangelib library to achieve this. I am able to the read email body and able to save file attachments (.pdf, .jpg, .xlsx), but facing issue on how to download Outlook items (.msg attachments. ex: someone provided an email approval or attached email has additional info etc..,). I read through exchangelib documentation, but it doesn't have any info on how to save an outlook attachment.
I have tried various ways by changing various modes 'w', 'wb' ..but no luck.
My code
# Read & Save Attachments code
for item in emails.all().order_by('-datetime_received')[:1]:
for attachment in item.attachments:
print('Number of Attachment found:', len(item.attachments))
if isinstance(attachment, FileAttachment):
local_path=os.path.join('C:/Attachments', 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)
elif isinstance(attachment, ItemAttachment):
name = str(attachment.name)+'.msg'
local_path=os.path.join('C:/Attachments/', name)
with open(local_path, 'w') as f:
f.write(attachment.item.body)
print('Saved attachment to', local_path)
Exchangelib Sample example
for item in a.inbox.all():
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
local_path = os.path.join('/tmp', attachment.name)
with open(local_path, 'wb') as f:
f.write(attachment.content)
print('Saved attachment to', local_path)
elif isinstance(attachment, ItemAttachment):
if isinstance(attachment.item, Message):
print(attachment.item.subject, attachment.item.body)
With above code, all i see is a file that is created with subject name, but 0 kb (with no content) and without extension (.msg) which is why i was concatenating the 'name' above.