Click here to Skip to main content
13,897,568 members
Click here to Skip to main content
Add your own
alternative version


171 bookmarked
Posted 25 Mar 2003

Hotmail using C# – A HTTPMail client under .NET

, 25 Mar 2003
Rate this:
Please Sign up or sign in to vote.
A C# client library for access Hotmail using the undocumented HTTPMail protocol.


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 basic knowledge of POP or SMTP it is possible to write proxies which 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 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 to the server.

Connecting to the HTTPMail Hotmail Gateway

The default HTTPMail gateway for Hotmail boxes is located at Although undocumented, the HTTPMail protocol is actually a standard WebDAV service. As we are using C#, we could use the TCP and HTTP classes provided by the .NET framework within the System.Net namespace. Since 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 which may be accessed directly. Note that in the code snippets contained within this article, variables suffixed with an underscore refer to member fields declared elsewhere within the sample code:

// Get the namespace.
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"?>
<D:propfind xmlns:D="DAV:"

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 = "";

// Build the query.
string folderQuery = null;
folderQuery += "<?xml version='1.0'?><D:propfind xmlns:D='DAV:' ";
folderQuery += "xmlns:h='' ";
folderQuery += "xmlns:hm='urn:schemas:httpmail:'><D:prop><h:adbar/>";
folderQuery += "<hm:contacts/><hm:inbox/><hm:outbox/><hm:sendmsg/>";
folderQuery += "<hm:sentitems/><hm:deleteditems/><hm:drafts/>";
folderQuery += "<hm:msgfolderroot/><h:maxpoll/><h:sig/></D:prop></D:propfind>";

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. Since 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 connection, set the PROPFIND request header to our XML-based query, and then send the request with a null body:

// Open a connection to the Hotmail server."PROPFIND", serverUrl, false, username, password);

// Send the request.
xmlHttp_.setRequestHeader("PROPFIND", folderQuery);

Parsing the Mailbox Folder List

The request sent to 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_.responseText;

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"?>

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 since 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.
  // Got an element?
  if(xml.NodeType == XmlNodeType.Element)
    // Get this node.
    string name = xml.Name;

    // Got the inbox?
    if(name == "hm:inbox")
      // Set folder.
      inboxUrl_ = xml.Value;

    // Got the send message page?
    if(name == "hm:sendmsg")
      // Set folder.
      sendUrl_ = xml.Value;

Once the URLs for the inbox and outbox which are valid for this session have been determined, it is possible send and retrieve and 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 in order 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 initalising 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"?>
<D:propfind xmlns:D="DAV:"

The followig C# code generates the XML query string:

// Build the query.
string getMailQuery = null;
getMailQuery += "<?xml version='1.0'?><D:propfind xmlns:D='DAV:' ";
getMailQuery += "xmlns:hm='urn:schemas:httpmail:' ";
getMailQuery += "xmlns:m='urn:schemas:mailheader:'><D:prop><D:isfolder/>";
getMailQuery += "<hm:read/><m:hasattachment/><m:to/><m:from/><m:subject/>";
getMailQuery += "<m:date/><D:getcontentlength/></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. Since 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."PROPFIND", folderUrl, false, null, null);
string folderInfo = xmlHttp_.responseText;

Following a successful request, the server will respond with an XML stream containing information for each MailItem contained within the folder.

        <m:from>Mark Anderson</m:from>
        <m:subject>RE: New Information</m:subject>
      <D:status>HTTP/1.1 200 OK</D:status>

Looking at the XML fragment above, we find that contained within each <D:response> node are a set of fields identifying the MailItem, including the <D:href> tag, which will later allow us to retrieve the item. We can again use System.XML.XmlTextReader to parse this XML text stream. We first initalise the stream reader:

// Holders.
MailItem mailItem = null;

// Load the Xml.
StringReader reader = new StringReader(folderInfo);
XmlTextReader xml = new XmlTextReader(reader);

Parsing Folder Information

In order the parse the XML in a single pass, we create a new MailItem instance on opening the <D:response> element, and store the instance when we reach the end of the tag. In between, we extract and set MailItem fields:

// Read the Xml.
  // 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.

        // Reset.
        mailItem = null;

    // Got an element?
    if(nodeType == XmlNodeType.Element)
      // Mail field.
      if(name == "D:href")
        // Load.
        mailItem.Url = xml.Value;

      // Mail field.
      if(name == "hm:read")
        // Load.
        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 within the given folder. For each MailItem we extract the following fields:

XML NodeDescription
D: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

Once 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 within the sample code takes a MailItem instance, and returns the content of the mailbox e-mail:

/// <summary>
/// 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."GET", mailUrl, false, null, null);

  // Send the request.

  // Get the response.
  string mailData = xmlHttp_.responseText;

  // Return the mail data.
  return mailData;

Sending New Mail

In order to retrieve mail, the LoadMail() method (see above) performs a HTTP/1.1 GET request. Similarly, a POST is sent to the sendmsg URL in order 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:

/// <summary>
/// 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 MIME format, but for demonstrations 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."POST", sendUrl_, false, null, null);

// Send the request.
xmlHttp_.setRequestHeader("Content-Type", "message/rfc821");

Given a valid destination mailbox, Hotmail will send the mail to our desired location.


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. Since 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.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

United Kingdom United Kingdom
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralHotmail has changed their focus to API.. Pin
Member 21860869-Aug-10 22:01
memberMember 21860869-Aug-10 22:01 
Generalme too, Access was denied Pin
UGRIT9-Nov-08 22:25
memberUGRIT9-Nov-08 22:25 
GeneralRe: me too, Access was denied Pin
charlyatx12-Apr-10 11:15
membercharlyatx12-Apr-10 11:15 
Generalnew HTTP server Pin
User 451897314-Nov-07 14:52
memberUser 451897314-Nov-07 14:52 
GeneralAccess Denied Pin
John . Adams13-Jun-07 7:52
memberJohn . Adams13-Jun-07 7:52 
GeneralDO NOT WORK Pin
cdemez3-Mar-06 22:29
membercdemez3-Mar-06 22:29 
GeneralRe: DO NOT WORK Pin
Umut Alev20-Apr-06 9:21
memberUmut Alev20-Apr-06 9:21 
GeneralAccess Denied Pin
Arunag21-Feb-06 2:12
memberArunag21-Feb-06 2:12 
GeneralCOMException Pin
DiegoPurgue7-Feb-06 7:57
memberDiegoPurgue7-Feb-06 7:57 
QuestionRe: COMException Pin
Paramesh Gunasekaran12-Feb-06 17:42
memberParamesh Gunasekaran12-Feb-06 17:42 
GeneralServerXMLHTTP class Pin
DiegoPurgue7-Feb-06 3:19
memberDiegoPurgue7-Feb-06 3:19 
GeneralRe: ServerXMLHTTP class Pin
folk00723-Jul-06 9:33
memberfolk00723-Jul-06 9:33 
Questionattachments? Pin
markm7516-Jan-06 7:47
membermarkm7516-Jan-06 7:47 
QuestionProblem with attachment Pin
Ariston Darmayuda16-Oct-05 5:37
memberAriston Darmayuda16-Oct-05 5:37 
GeneralSystem.Unauthorized Access Exception Pin
NortonC13-Oct-05 9:20
memberNortonC13-Oct-05 9:20 
GeneralError while trying to connect Pin
allenmpcx29-Sep-05 8:43
memberallenmpcx29-Sep-05 8:43 
GeneralA Comment About Comments Pin
Anonymous21-Aug-05 10:10
memberAnonymous21-Aug-05 10:10 
GeneralRe: A Comment About Comments Pin
Anonymous23-Sep-05 9:43
memberAnonymous23-Sep-05 9:43 
GeneralRe: A Comment About Comments Pin
Member 28828606-Apr-06 4:32
memberMember 28828606-Apr-06 4:32 
GeneralRe: A Comment About Comments Pin
mipozoo24-Sep-05 4:58
membermipozoo24-Sep-05 4:58 
GeneralDelete message Pin
Anonymous15-Aug-05 9:46
memberAnonymous15-Aug-05 9:46 
GeneralRe: Delete message Pin
Babboo27-May-06 2:39
memberBabboo27-May-06 2:39 
Generalgood work Pin
Ahmed Galal3-Aug-05 23:24
memberAhmed Galal3-Aug-05 23:24 
GeneralEmpty response Pin
jlisenberg1-May-05 6:33
memberjlisenberg1-May-05 6:33 
GeneralRe: Empty response Pin
Umut Alev26-Jul-05 23:22
memberUmut Alev26-Jul-05 23:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190306.1 | Last Updated 26 Mar 2003
Article Copyright 2003 by kais
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid