2
votes

How do you access the XML API with Python to create calendar events in a Microsoft Office 365 account?

I have a hosted account on http://outlook.office365.com, and I'm trying to use the Python library https://github.com/linkedin/pyexchange (using the sample code almost verbatim) to create calendar events, but Outlook refuses my credentials with the error, "Unable to connect to Exchange: HTTP Error 401: Unauthorized"

I'm using the endpoint https://outlook.office365.com/EWS/Exchange.asmx, with the username and password I normally use to login to the web UI.

Do I need to specially setup or configure my account before I can access it from the API?

2

2 Answers

5
votes

Your outlook probably does not use NTLM Authentication anymore. (Sources: here, here and here)

I faced the same issue after our accounts were migrated from on-prem to O365 and had to use another library to access the calendar on exchange. I used the O365 library here: https://pypi.org/project/O365

Follow the docs to create an register and authenticate your application in Azure, then you should be able to access your calendar as before with the sample code below:

from O365 import Account
from datetime import datetime
credentials = ('your_client_id', 'client_secret')

scopes = ['https://outlook.office365.com/Calendars.Read']
account = Account(credentials)

schedule = account.schedule()
calendar = schedule.get_default_calendar()

q = calendar.new_query('start').greater_equal(datetime(2019, 5, 20))
q.chain('and').on_attribute('end').less_equal(datetime(2019, 10, 24))

events = calendar.get_events(query=q, include_recurring=True)

for event in events:
    print(event.subject)
3
votes

For username usually office365 accepts your email on office 365 2013 version. for 2010 your domain and username.

from pyexchange import Exchange2010Service, ExchangeNTLMAuthConnection

URL = u'https://outlook.office365.com/EWS/Exchange.asmx'
USERNAME = u'domain\\username' #here write full email address
PASSWORD = u"YOURPASS"

# Set up the connection to Exchange
connection = ExchangeNTLMAuthConnection(url=URL,
                                    username=USERNAME,
                                    password=PASSWORD)

service = Exchange2010Service(connection)

Here how I connect to the office 2013 outlook api:

url = 'https://outlook.office365.com/api/v1.0/me/events?$Select=Start,End'
user = '[email protected]'

pwd = getpass.getpass('Please enter your AD password: ')
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_data)
auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % auth)
request.add_header('Content-Type', 'application/json')
request.add_header('Accept', 'application/json')