Monday, March 19, 2012

Calling the JangoMail Web Service in Python

Python is a language that seems to make so many mundane programming tasks easy. Unfortunately, some python libraries are perhaps less fully developed than the libraries of other languages. This is certainly the case of the python soap libraries SOAPpy and SUDS. In my experience, both libraries are painfully buggy. In python, I think it's easier just to use httplib and build the xml manually. Luckily, python's other conveniences make that pretty easy!

In this example, we build an xml template for calling Groups_GetList_String. To test it with your own account, just insert your own JangoMail/JangoSMTP credentials. Download the source code for this example to start your own integration!

import sys
import httplib

# setup the sml template xml for a call to Groups_GetList_String
SM_TEMPLATE = """<?xml version="1.0" encoding="utf-8"?>
    <Groups_GetList_String xmlns="">

# fill in the parameters for our call
SoapMessage = SM_TEMPLATE%("Your JangoMail/JangoSMTP Username", 
              "Your Password", "\n", " - ", "")

# examine the soap message that we have constructed
print SoapMessage

# insert the proper values into the header
webservice = httplib.HTTP("")
webservice.putrequest("POST", "/api.asmx")
webservice.putheader("Host", "")
webservice.putheader("User-Agent", "Python post")
    "application/soap+xml; charset=\"UTF-8\"")
webservice.putheader("Content-length", "%d" % len(SoapMessage))

# get the response and print it
statuscode, statusmessage, header = webservice.getreply()
print "Response: ", statuscode, statusmessage
print "headers: ", header
res = webservice.getfile().read()
print res