Sending an Email on Microsoft Exchange with Python
27 Jan 2014
Part 2: Getting the Python EWS Client to Send an Email
Now that I’ve got a client connect to the Exchange server, I can actually use the SOAP API methods as documented in the WSDL and on Microsoft’s documentation.
Suds has great built-in methods and classes for working with SOAP, but as this post confirms, bugs in both Suds and EWS mean that I’ll have to manually build the XML and inject it directly into the message.
So far, I have code that will connect a Suds client to my exchange server and send an XML message:
Now, we just need to tell it what to send in that message.
Building the XML Message
There are all kinds of things you can talk to EWS about, but I just want to talk about emails.
First, I wanted to place a copy in my SentItems folder, so I added
In my first iteration, I had the body sent as text but I wanted to replace it with an HTML email template to make it prettier. This was tough for me to figure out; I kept getting XML validation errors. Eventually, I learned about CDATA, a tag that tells the XML parser to ignore whatever’s inside it.
I replaced the Body tag with:
And will replace the #Body# with some HTML from an email template later.
Lastly, I put in some information about an automatic Reminder to get the final message:
Each of those #Variable# tags I put in the XML will be string-replaced on the Python side.
Putting Variables into the Message
I wrote a quick little function to take a list of tuples and a template text and replace the text in the template:
Now that I have XML as a big string, I can send my message: