pythonflaskflask-mailexchangelibdistribution-list

Port issue while using exchangelib in python


I have a webapp built using flask. One of the functionality was sending emails. I was using Flaskmail and it was working fine.

But now, I have a requirement which needs me to expand a distribution list. I came across exchangelib library and tried using it, But I am unable to establish a connection.

The error that i am encountering is :

exchangelib.errors.TransportError: HTTPSConnectionPool(host='<mail_server_name>', port=443):
 Max retries exceeded with url: /EWS/Exchange.asmx (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000001B71F194040>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

The configuration I was using for Flask mail was :

MAIL_SERVER='<mail_server_name>'
MAIL_PORT=587
MAIL_USERNAME='<user-name provided by exchange admin>'
MAIL_PASSWORD='<password>'
MAIL_USE_TLS=True
MAIL_USE_SSL=False

I had saved this configuration in a file - config.cfg and loading it. Using the same configuration, I am trying to use exchangelib. The exchangelib configuration is :

app = Flask(__name__,template_folder = 'Templates',static_folder='Static') 
app.config.from_pyfile('config.cfg')


cred = Credentials(username=app.config['MAIL_USERNAME'],password=app.config['MAIL_PASSWORD'])
config = Configuration(server=app.config['MAIL_SERVER'], credentials=cred)
account = Account(primary_smtp_address='<admin_email_address>', config=config, autodiscover=False, access_type=DELEGATE)

What's going wrong? I noticed that the error message had the wrong port (443). While I was connecting through port 587 on Flask mail, exchangelib is using port 443. Is this the reason why the connection is being refused by the target machine?

If so, How do I connect using port 587 on exchangelib?


Solution

  • exchangelib uses the EWS protocol, where it seems your previous code connected to the SMTP protocol.

    You need to find out at which URL your Exchange server exposes the EWS protocol. Your Exchange admins can most likely help you with that.