Author: Kais Dukes
The great thing about the POP mail protocol is that it is a well-documented open standard, making writing a mail client to collect mail from a POP box a relatively painless process. Armed with a basic knowledge of POP or SMTP, it is possible to write proxies that do a variety of useful things, such as filter out spam or junk mail, or provide an e-mail answering machine service. Unfortunately, in trying to write a standalone client for Hotmail, the world's most popular Web-based mailing system , The Fact That No Pop Gateway EXISTS RAPIDLY BECOMES A Problem.
Despite the lack of POP support, connecting to Hotmail without using a Web browser is possible. Outlook Express allows users to retrieve, delete, move, and send messages, connecting directly to a standard Hotmail or MSN mailbox. By using a HTTP packet sniffer, IT IS Possible To Monitor Communication Between Outlook Express and hotmail, Making It Possible To Determine How The Direct Mailbox Connection is Made.
Outlook Express uses an undocumented protocol commonly referred to as HTTPMail, allowing a client to access Hotmail using a set of HTTP / 1.1 extensions. This article explains some of the features of HTTPMail, and how best to connect to Hotmail by using a C # client. The sample source code accompanying this article uses COM interop to leverage XMLHTTP as the transport service. The XMLHTTP component provides a complete HTTP implementation, including authentication together with ability to set custom headers before sending HTTP requests server-side.
Connecting to the httpmail Hotmail Gateway
The default HTTPMail gateway for Hotmail boxes is located at http://services.msn.com/svcs/hotmail/httpmail.asp. Although undocumented, the HTTPMail protocol is actually a standard WebDAV service. Because we are using C #, we could use the TCP and HTTP classes provided by the .NET framework within the System.Net namespace. Because we are working with WebDAV, it is simpler to use XMLHTTP to connect to Hotmail under C #. Referencing the MSXML2 component provides an interop assembly that may be accessed Directly. Note That In The Code Snippets Contaed With Article
USING MSXML2;
...
// CREATE The Object.
XMLHTTP_ = New XMLHTTP ();
In order to connect to a secure server, the WebDAV protocol requires HTTP / 1.1 authentication. The initial request sent by a HTTPMail client uses the WebDAV PROPFIND method to query for a set of properties. These include the URL of the Hotmail advertisement bar together with The Location of Mailbox Folders:
XML Version = "1.0"?>
XMLns: h = "http://schemas.microsoft.com/hotmail/" XMLns: hm = "URN: Schemas: httpmail:">> D: PrOP> D: propfind> Sending The Initial Request Via Xmlhttp Begins by Specifying The WebDAV Server URL, And Generating The Initial XML Request: // Specify The Server URL. String serverURL = "http://services.msn.com/svcs/hotmail/httpmail.asp" ;// build the query. String folderQuery = null; FolderQuery = " XML Version = '1.0'?> FolderQuery = "XMLns: h = 'http://schemas.microsoft.com/ Hotmail / '" FolderQuery = "XMLns: hm = 'URN: Schemas: httpmail:'> FolderQuery = " FolderQuery = " FolderQuery = " The Httpxml Component Provides An Open () Method Used To Establish A Connection To a HTTP Server: Void Open (String Method, String Url, Bool Async, String User, String Password; The first argument specifies the HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND. To connect to the Hotmail gateway, we specify the PROPFIND method to query the mailbox. This and other HTTP methods are used to retrieve folder information, collect mail items, and send new mail. Note that the open () method allows for the possibility of asynchronous calls (enabled by default), which is preferred for a graphical mail client. Because the sample code is a console application, we set this parameter to false. For authentication, we specify a username and password. Note that under XMLHTTP, the component will display a login window if these parameters are missing and the site requires authentication. to connect to the Hotmail gateway, we open the . XMLHTTP_.Open ("PropFind", ServerURL, False, Username, Password); // dend the request. XMLHTTP_.SetRequestHeader ("PropFind", FolderQuery; XMLHTTP_.SEND (NULL); Parsing The Mailbox Folder List The request sent to services.msn.com is typically redirected several times. After load balancing, we are finally connected to a free Hotmail server, and authenticated. This redirection, with appropriate authentication, is handled by the XMLHTTP component. Once connected, the server will also ask us to set various cookies, valid for the current session (again this is all handled automatically by XMLHTTP) Upon sending the initial connection request, the server will return an XML-based response.: // Get the response. String folderlist = xmlhttp_.responsext; The Returned Response Will Contain, Among Other Useful Information, The Url Locations of The Folders WITHIN THE Mailbox. For example: XML Version = "1.0" encoding = "Windows-1252"?> ... hm: contacts> hm: inbox> hm: sendmsg> hm: SentItems> hm: deleditems> hm: msgfolderroot> ... D: PrOP> D: response> D: MultiStatus> In the sample console application, the two mailbox folders that we are interested in are the inbox and sendmsg folders, used to retrieve and send mail items, respectively. There are various ways to parse XML under C #, but because we are confident of our XML Structure, System.xml.xmlTextReader Provides Fast, Forward-Only Access. We initialise the xml reader by Converting The XML String Data Into A String Stream: // initiate. Inboxurl_ = NULL; Sendurl_ = NULL; // load the xml. StringReader Reader = New StringReader (FolderList); XmlTextReader XML = New XMLTextReader (Reader); THE XML IS PARSED BY ITERATING THROUGH Each Node, Picking Out The HM: Inbox and HM: Sendmsg Nodes: // read the xml. While (xml.read ()) { // got an element? IF (XML.NodeType == XMLNodetype.element) { // Get this node. String name = Xml.name; // got the inbox? IF (Name == "HM: Inbox) { // SET Folder. Xml.read (); Inboxurl_ = Xml.Value; } // got the send message page? IF (name == "hm: sendmsg") { // SET Folder. Xml.read (); Sendurl_ = Xml.Value; } } } After the Urls for the Inbox and Outbox That Are Valid for this Session Have Been Determined, IT IS Possible To Send and Retrieve E-MAIL. ENUMERATING FOLDER MAILITEMS Given the URL of a mailbox folder (such as the Inbox folder), we can direct a WebDAV request to the folder's URL to list mail items within the folder. The sample console application defines a managed type MailItem, used to store mail information for a Folder Item. Folder Enumeration Begins by Initialising An Array Of MailItems: // initiate. ArrayList mailitems = new arraylist (); To Request Mail Item Data, Such as The Mail Subject, and The To and from Addresses, We generate the following xml-based WebDAV Query: XML Version = "1.0"?> XMLns: M = "URN: Schemas: Mailheader:"> D: PrOP> D: propfind> The Following C # code generates the xml query string: // build the query. String getMailQuery = null; GetmailQuery = " XML Version = '1.0'?> GetmailQuery = "XMLns: hm = 'URN: Schemas: httpmail:' GetmailQuery = "XMLns: m = 'URN: Schemas: Mailheader:'> GetMailQuery = " D: prop> d: propFind> This request is sent via XMLHTTP using the PROPFIND method, similar to the way in which the mailbox folder list was requested above. This time round, we set the request body to be the query, and folder information is returned. Because we have already been Authenticated for this session, There is no need to resupply the username and password on the xmlhttp open () call: // Get the mail info. XMLHTTP_.Open ("PropFind", FolderURL, FALSE, NULL, NULL; Xmlhttp_.send (getMailQuery); String folderinfo = xmlhttp_.responsext; . http://sea1.oe.hotmail.com/cgi-bin/hmdata / ... D: href> D: getContentLength> D: PrOP> D: PropStat> D: response> ... Looking at the XML fragment above, we find that contained within each MailItem MailItem = NULL; // load the xml. StringReader Reader = New StringReader (FolderInfo); XmlTextReader XML = New XMLTextReader (Reader); Parsing Folder Information TO PARSE THE XML IN A SINGLE Pass, WE CREATE A NEW MALITEM Instance ON Opening The // read the xml. While (xml.read ()) { // sections. String name = Xml.name; XMLNodetype Nodetype = XML.NODETYPE; // e-mail? IF (name == "d: response") { // start? IF (nodetype == xmlnodetype.element) { // CREATE A New Mail Item. MailItem = new mailitem (); } // end? IF (nodetype == xmlnodetype.endelement) { // Store the last mail. MailItems.Add (MailItem); // reset. MailItem = NULL; } } // got an element? IF (nodetype == xmlnodetype.element) { // Mail Field. IF (name == "d: href") { // load. Xml.read (); Mailitem.url = Xml.Value; } // Mail Field. IF (Name == "HM: Read") { // load. Xml.read (); Mailitem.isread = (XML.Value == "1"); } // Load Other MailItem Fields, ETC ... } } The Above Code (Part of That Found The Sample Console Application) ENUMERATES The MailItems Found With Given Folder. For Each MailItem WE Extract The Following Fields: XML NodeDescriptionD: hrefThe URL used to retrieve this HttpMail item.hm:readFlag set if this e-mail is read.m: toWho the mail was sent to.m: fromWho the mail was sent from.m: subjectThe mail subject.m: dateTimestamp in the format [date] T [time] D: getcontentlengthThe size of this e-mail (in bytes) .The sample code reads the XML nodes as set out above, to extract information for each mail item found within the returned Folder Info XML Data Stream. Retrieving Folder Mail After MailItems in the folder have been enumerated, the mail URL (valid for the given session) for a MailItem can be used to retrieve the actual e-mail. This is done by sending a HTTP / 1.1 GET request to the Hotmail server, at The Given Url. The loadmail () Function Defined Wtem Instance, And Returns The Content of the Mailbox E-mail: /// /// loads the given mail item. /// summary> Public String Loadmail (MailItem MailItem) { // Get the URL. String mailurl = mailitem.URL; // Open a connection to the Hotmail Server. XMLHTTP_.Open ("Get", Mailurl, False, Null, NULL; // dend the request. XMLHTTP_.SEND (NULL); // Get the response. String maildata = xmlhttp_.reesponsext; // Return The Mail Data. Return maildata; } Sending New Mail To retrieve mail, the LoadMail () method (see above) performs a HTTP / 1.1 GET request. Similarly, a POST is sent to the sendmsg URL to send an e-mail from the Hotmail box. The sample console application also contains a SendMail () Method Which Maybe Invoked ONCE Connected to the mailbox: /// /// sends an e-mail. /// summary> Public void sendmail (String from, String fromname, String to, String Subject, String Body) { ... } We Begin by Setting Up A Quote String (Used Later), AS Well Generating A Mail Time Stamp: // Quote Character. String quote = "/ u0022"; // generate the time stamp. DateTime now = datetime.now; String TimeStamp = now.toString ("DDD, DD MMM YYYY HH: MM: SS"); The Httpmail Protocol Follows An SMTP-LIKE Communication Scheme (See RFC 821). Outlook Express Sends Out Mail In The Mime Format, But for Demonstration Purposes, We Simply Send A Plain Text E-mail: // build the post body. String postbody = NULL; // Dump mail headers. Postbody = "Mail from: <" from "> / r / n"; Postbody = "RCPT TO: <" to "> / r / n"; Postbody = "/ r / n"; PostBody = "from:" quote fromname quote " <" from "> / r / n "; Postbody = "TO: <" to "> / r / n"; Postbody = "Subject:" Subject "/ R / N"; Postbody = "Date:" TimeStamp "-0000 / n"; Postbody = "/ r / n"; // Dump mail body. Postbody = body; To send the mail, we need to set the Content-Type request header to message / rfc821, indicating that this request contains a body which follows RFC 821. We POST the request body generated above to the sendmsg URL obtained during connection time: // Open the connection. XMLHTTP_.Open ("Post", Sendurl_, False, Null, NULL; // dend the request. XMLHTTP_.SetRequestHeader ("Content-Type", "Message / RFC821); XMLHTTP_.SEND (PostBody); Given a Valid Destination Mailbox, Hotmail Will Send The Mail To Our Desired Location.conClusion Hotmail is the world's largest provider of free, Web-based e-mail. However, the only non-Web mail client with direct access to Hotmail is Outlook Express. Because the HTTPMail protocol is undocumented, other vendors are discouraged from providing a similar service . In this article, we saw how to connect to a Hotmail mailbox, enumerate inbox mail items, and send and retrieve e-mail, using C # and the XMLHTTP component. Sample code accompanying this article contains a .NET assembly, demonstrating that connecting to Hotmail Via Httpmail Can Be As Simple As Working With Any Other Mail Protocol Such As Pop3, Imap4, or SMTP. About the Author Kais Dukes is currently working with a leading derivatives pricing specialist, where he is helping to build one of the world's largest fanancial systems that uses .NET technology. He is finishing a Ph.D. in Artificial Intelligence, and is also completing a book on Templates and generative programming in C . A Selection of his more............................ .. Downloads Download Sample C # Source Code - 9 KB