Dias
Dias

Reputation: 51

Error "Failed to create cached protocol with key.." when trying to connect to Exchange mail account using python

Good day. I have a python script which checks mailbox for unread messages. If there are unread messages with attachments it then executes some code(excel automation). It used to be working well; however, today I encountered this error while executing script:

Failed to create cached protocol with key ('********/EWS/Exc hange.asmx', Credentials('*******', '********')): HTTPSConnectio nPool(host='*******', port=443): Max retries exceeded with url: /EW S/Exchange.asmx (Caused by SSLError(SSLCertVerificationError("hostname 'mail.example.com' doesn't match either of '*.example.com', 'example.com'")))

Where example.com is company's server.

I searched for some answers and encountered an adivce saying I should set veryfy-ssl to False (Account). When I do that, I do not receive the error from the command line anymore but the script just finishes in 1 sec and does nothing.

What can be the issue here? I have not done any changes to the code, so is it mail server's fault? Below is the snippet of the code which gets attachment from mail:

def get_attachments(login, password, path):
    files_list = []
    credentials = Credentials(
    username=login,  
    password=password
    )
    config = Configuration(server=settings.server, credentials=credentials)
    account = Account(primary_smtp_address=login, 
    config=config, autodiscover=False, access_type=DELEGATE)
    unread = account.inbox.filter(is_read=False) 
    attachment_counter = 0
    for msg in unread:
        msg.is_read = True
        msg.save()
        for attachment in msg.attachments:
            fpath = os.path.join(path, attachment.name)
            if os.path.exists(fpath):
                attachment_counter += 1
                fpath = os.path.join(path, (str(attachment_counter) + attachment.name))
            if attachment.name.split(".")[-1].lower() in ['xlsx', 'xls']:
                with open(fpath, 'wb') as f:
                   f.write(attachment.content)
                   files_list.append(fpath)
    return files_list

Upvotes: 0

Views: 1119

Answers (1)

Erik Cederstrand
Erik Cederstrand

Reputation: 10220

The error is caused by an invalid SSL certificate installed on your Exchange server - the certificate is not valid for the domain name it is served from. You can disable SSL validation at your own peril. See instructions for doing so at https://github.com/ecederstrand/exchangelib/blob/master/README.md#proxies-and-custom-tls-validation.

Your script doesn't print any output, so it's not really possible to know whether it works as intended or not. 1 second is sufficient on a fast Exchange server to check your inbox for unread emails. Maybe you just don't have any unread email, or there were no unread emails with Excel attachments?

Upvotes: 0

Related Questions