Read emails and download attachment from Microsoft Exchange Server

Zayn malik picture Zayn malik · Apr 19, 2017 · Viewed 8.9k times · Source

connect-to-exchange-mailbox-with-python/3072491....I have refereed the following link to connect to Exchange Online and download attachments and read mails on windows(using Python and exchangelib library). Now I want to accomplish the same task on CentOS but when I manually download the exchangelib library and install it. Whenever I try to import exchangelib, it throws an error like:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "exchangelib/__init__.py", line 2, in <module>
    from .account import Account  # noqa
  File "exchangelib/account.py", line 8, in <module>
    from cached_property import threaded_cached_property
ImportError: No module named cached_property

What might be the problem?

My main objective is to read emails and download them. No imap/pop3 server address is available. Is there an alternative to exchangelib?

from exchangelib import DELEGATE, Account, Credentials

credentials = Credentials(
    username='MYWINDOMAIN\\myusername', 
    password='topsecret'
)
account = Account(
    primary_smtp_address='[email protected]', 
    credentials=credentials, 
    autodiscover=True, 
    access_type=DELEGATE
)
# Print first 100 inbox messages in reverse order
for item in account.inbox.all().order_by('-datetime_received')[:100]:
    print(item.subject, item.body, item.attachments)

I have used this code in Windows. Help me out with Linux.

Answer

Martin Thoma picture Martin Thoma · Aug 1, 2017

This is how you read all emails and store all attachments with exchangelib:

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)

Related: How can I send an email with an attachment with Python and Microsoft Exchange?