Home » Technology

Read email from Exchange Server remotely using .Net

5 August 2009 One Comment

Due to extensive use of email and blackberry, our team get requirement to add new module to enable approval routing via email. Concept is when user click a button on web application, system then will send email to approvers base on  pre-define approval routing scheme. Thus approver then will read email and click links within email, which basically a shortcut to send email to specific account with pre-defined subject. A batch process is being set to run every 10 minutes to read any email is being sent by approver on our exchange server and read specific pattern on subject to define if a request would be approved or rejected.

Most challenging part is to read exchange server, since our POP3 access is closed due to security reason, so further reading on this post will describe on how we achieve that through combination of .Net, Exchange Server, XML and DAV access.

Object Reference

Before we start, this project will use some reference on our .Net project, they are

System.Xml
System.Xml.Xsl
MSXML2

MSXML2 is not standard library, it we for some reason couldn’t find it on our system, then we can obtain it for free from MSDN. Just type for “MSXML download” and "MSDN will show you Url for latest update.

Or else we can use .Net HttpWebRequest and HttpWebResponse class instead of using MSXML2, but due to those 2 classes complexity on handling such stream returned, I prefer to have it with MSXML :)

Exchange Server DAV Url and Operation

To connect to Exchange server, we will use DAV access, basically it will send a HTTP request to DAV Url and get the response. So, we need to know DAV Url for our exchange server, DAV url would normally have pattern as follow: http://exchangeservername/exchange/userlogin/inbox.

Easiest way to get our exchangeserver name if by looking at our outlook account setting,  on Outlook –> Tools –> Account Setting –> Change, see Microsoft Exchange Server textbox as below image, that value  would be our exchange server name.

outlookaccountsetting

Ok, now we know what is our Exchange Server name, now based on that we can figure out some DAV link where we can use to do some operation. Those are:

http://exchangeservername/exchange/userlogin/inbox
PROPFIND, to read all inbox

http://exchangeservername/exchange/userlogin/inbox/emailsubject.eml
DELETE, to delete specific message
X-MS-ENUMATTS, to get list of attachment

http://exchangeservername/exchange/userlogin/inbox/attachment.file
GET, to retrieve email attachment

Connecting to Exchange Server

Below are sample of full function on how we can read exchange email remotely. For other operations like delete or iterate attachment on a message we can modify this code on line 154.

  137 Public Function InboxReadAll() As InboxMessageDataTable

  138         Dim ret As New InboxMessageDataTable

  139 

  140         ‘– Read settings information from web config

  141         Dim ServiceUserId As String = WebConfigurationManager.AppSettings("ServiceLoginId")

  142         Dim ServicePassword As String = WebConfigurationManager.AppSettings("ServicePassword")

  143         Dim ServiceDomain As String = WebConfigurationManager.AppSettings("ServiceDomain")

  144         Dim ServiceInbox As String = String.Format(WebConfigurationManager.AppSettings("ServiceInbox"), ServiceUserId)

  145         Dim LoginIdFull As String = String.Format("{0}\{1}", ServiceDomain, ServiceUserId)

  146 

  147         ‘– variable to handle operation

  148         Dim oXmlHttp As New MSXML2.ServerXMLHTTP40

  149         Dim xmlDOMParamsAttachement As New MSXML2.DOMDocument40

  150         Dim xmlDOMParams As New System.Xml.XmlDataDocument

  151         Dim xmlResponse As XmlNodeList

  152 

  153         ‘– build DAV connection URL

  154         Dim ConnectingUrl As String = String.Format("{0}/inbox", ServiceInbox)

  155 

  156         With oXmlHttp

  157 

  158             ‘– Open DAV Access

  159             .open("PROPFIND", ConnectingUrl, False, LoginIdFull, ServicePassword)

  160             .setRequestHeader("Depth", "1")

  161             .setRequestHeader("Content-type", "xml")

  162             .send()

  163 

  164             ‘– Retrieve request response and load it on XML

  165             Dim Str As String = oXmlHttp.responseText

  166             xmlDOMParams.LoadXml(Str)

  167 

  168             ‘– Get response part of XML

  169             xmlResponse = xmlDOMParams.GetElementsByTagName("a:response")

  170 

  171             ‘– Prepare namespace manager, as response will be coded with some namespace on its element

  172             Dim xmlNs As New XmlNamespaceManager(xmlDOMParams.NameTable)

  173             xmlNs.AddNamespace("a", "DAV:")

  174             xmlNs.AddNamespace("d", "urn:schemas:mailheader:")

  175             xmlNs.AddNamespace("e", "urn:schemas:httpmail:")

  176 

  177             ‘– iterate each node and save it to message datatable

  178             For Each node As XmlNode In xmlResponse

  179                 Dim xmlHref As XmlNode = node.SelectSingleNode("./a:href", xmlNs)

  180                 If Not xmlHref Is Nothing Then

  181                     If xmlHref.InnerText.ToLower.EndsWith(".eml") Then

  182                         Dim newInboxMsg As InboxMessageRow = ret.NewInboxMessageRow

  183                         With newInboxMsg

  184                             .URL = xmlHref.InnerText

  185                             .Subject = node.SelectSingleNode("//d:subject", xmlNs).InnerText

  186                             .FromEmail = node.SelectSingleNode("//e:fromemail", xmlNs).InnerText.ToLower

  187                             .Message = node.SelectSingleNode("//e:textdescription", xmlNs).InnerText

  188                         End With

  189                         ret.Rows.Add(newInboxMsg)

  190                     End If

  191                 End If

  192             Next

  193         End With

  194 

  195         Return ret

  196     End Function

Bookmark and Share

Related article(s)

If you think this post is interesting, maybe you would consider to subscribe to my feed by click here or keep update with my newest post via email

One Comment »

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.