By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,635 Members | 1,699 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,635 IT Pros & Developers. It's quick & easy.

exchange + attachments

P: 3
Dear All,

With the code below I am able to successfully pull out e-mails by using the sql query defined with the webdav's search method. However, I am very unclear how to pull the attachments from an e-mail. I have gone through various tutorials and based on which I have written the code below using the "X-MS-ENUMATTS" method. Also printed the output below. I would appreciate if you help me from the point where I can pull the attachment from the email and save it locally.

OUTPUT:-

http://extra/Exchange/user/Inbox/email.EML/1_multipart_xF8FF_
2_attachment.docHTTP/1.1 200 OKattachment.doc1-1application/msword8attachment205440 attachment.docattachment.doc


CODE:-

Option Explicit On
Option Strict On
Imports System.Reflection
Imports System.Xml


Module Module1

Sub Main()

' Variables
Dim Request As System.Net.HttpWebRequest
Dim Response As System.Net.HttpWebResponse
Dim MyCredentialCache As System.Net.CredentialCache
Dim strPassword As String
Dim strDomain As String
Dim strUserName As String
Dim strRootURI As String
Dim strQuery As String
Dim bytes() As Byte
Dim RequestStream As System.IO.Stream
Dim ResponseStream As System.IO.Stream
Dim XmlReader As System.Xml.XmlTextReader
Dim y As String

Try
' Initialize variables.
strUserName = "user"
strPassword = "pass"
strDomain = "dubaimerc.int"
strRootURI = "http://extra/Exchange/user/Inbox"

' Build the SQL query.
strQuery = "<?xml version=""1.0""?>" & _
"<D:searchrequest xmlns:D = ""DAV:"" >" & _
"<D:sql>SELECT ""dav:href"",""dav:urn:schemas:httpmail:fromemail" " FROM scope('shallow traversal of """ & _
strRootURI & """ ')"


strQuery = strQuery & " WHERE ""urn:schemas:httpmail:fromemail"" = 'cp@cp.com' and ""urn:schemas:httpmail:read""=true ORDER BY ""urn:schemas:httpmail:datereceived"" DESC"
strQuery = strQuery & "</D:sql></D:searchrequest>"




' Create a new CredentialCache object and fill it with the network
' credentials required to access the server.
MyCredentialCache = New System.Net.CredentialCache
MyCredentialCache.Add(New System.Uri(strRootURI), _
"NTLM", _
New System.Net.NetworkCredential(strUserName, strPassword, strDomain) _
)

' Create the SEARCH HttpWebRequest object.
Request = CType(System.Net.WebRequest.Create(strRootURI), _
System.Net.HttpWebRequest)

' Add the network credentials to the request.
Request.Credentials = MyCredentialCache

' Specify the SEARCH method.
Request.Method = "SEARCH"

' Encode the body using UTF-8.
bytes = System.Text.Encoding.UTF8.GetBytes(strQuery)

' Set the content header length. This must be
' done before writing data to the request stream.
Request.ContentLength = bytes.Length

' Get a reference to the request stream.
RequestStream = Request.GetRequestStream()

' Write the message body to the request stream.
RequestStream.Write(bytes, 0, bytes.Length)

' Close the Stream object to release the connection
' for further use.
RequestStream.Close()

' Set the Content Type header.
Request.ContentType = "text/xml"

' Send the SEARCH method request and get the
' response from the server.
Response = CType(Request.GetResponse(), System.Net.HttpWebResponse)

' Get the XML response stream.
ResponseStream = Response.GetResponseStream()

' Create the XmlTextReader object from the XML
' response stream.
XmlReader = New System.Xml.XmlTextReader(ResponseStream)

' Read through the XML response, node by node.

While (XmlReader.Read())

XmlReader.GetAttribute("a:href")


' Look for the opening DAV:href node. The DAV: namespace is
' typically assigned the a: prefix in the XML response body.

If XmlReader.Name = "a:href" Then

' Advance the reader to the text node.
XmlReader.Read()

' Display the value of the DAV:href text node.
Dim emailName As String
emailName = XmlReader.Value

Dim HttpWebRequest As MSXML2.XMLHTTP40



Dim GetAttachmentsListXML1 As String

HttpWebRequest = New MSXML2.XMLHTTP40
With HttpWebRequest
.open("X-MS-ENUMATTS", emailName, False, strUserName, strPassword)
.setRequestHeader("Depth", "1")
.setRequestHeader("Content-type", "xml")
.send()

GetAttachmentsListXML1 = HttpWebRequest.responseText
Dim x As New Xml.XmlDocument
Dim strAttachmentPath As String
x.LoadXml(GetAttachmentsListXML1)
strAttachmentPath = x.DocumentElement.InnerText

'y = x.DocumentElement.InnerText

Dim z As Object
z = ReadAnAttatchment(strAttachmentPath, strUserName, strPassword)



Console.WriteLine(strAttachmentPath)
End With

Console.WriteLine("")
HttpWebRequest = Nothing
' Advance the reader to the closing DAV:href node.
XmlReader.Read()
End If
End While


Console.ReadLine()
' Clean up.
XmlReader.Close()
ResponseStream.Close()
Response.Close()




Catch ex As Exception

' Catch any exceptions. Any error codes from the
' SEARCH method requests on the server will be caught
' here, also.
Console.WriteLine(ex.Message)
Console.Read()
End Try

End Sub
Public Function ReadAnAttatchment(ByVal sHREF As String, ByVal sUserName As String, ByVal sPassword As String) As Object

Dim HttpWebRequest As MSXML2.XMLHTTP30

HttpWebRequest = New MSXML2.XMLHTTP30
HttpWebRequest.open("GET", sHREF, False, sUserName, sPassword)

HttpWebRequest.send()

ReadAnAttatchment = HttpWebRequest.responseText ' Returns as text
'ReadAnAttatchment = HttpWebRequest.responseBody ' Returns as encoded
Return ReadAnAttatchment

HttpWebRequest = Nothing
End Function

End Module
Aug 28 '07 #1
Share this Question
Share on Google+
3 Replies


kenobewan
Expert 2.5K+
P: 4,871
Here is a thread that may help:
WebDAV download attachments

Hint: try using the site search :).
Aug 28 '07 #2

P: 3
i have done lot of searches on this topic for almost a week now...

i am able to now get the two nodes values ... is there any help you can offer?
Aug 29 '07 #3

P: 3
Please any help on this issue we are facing will highly be appreciated..

My code is able to read all e-mails and using prase fucntion I am able to retreive the URI for the attahcment, but when I try to donwload the attachment from the URI, it throws a 401 unauthroized error..and than reads the next e-mail.

can you suggest what maybe wrong, the code is as follows:

Option Explicit On
Option Strict Off

Imports System.Reflection
Imports System.Xml
Imports System.IO
Imports System.Text
Imports System.Net.WebClient
Imports System.Text.RegularExpressions
Imports System.Net


Module Module1

Sub Main()

' Variables
Dim Request As System.Net.HttpWebRequest
Dim Response As System.Net.HttpWebResponse
Dim MyCredentialCache As System.Net.CredentialCache
Dim strPassword As String
Dim strDomain As String
Dim strUserName As String
Dim strRootURI As String
Dim strQuery As String
Dim bytes() As Byte
Dim RequestStream As System.IO.Stream
Dim ResponseStream As System.IO.Stream
Dim XmlReader As System.Xml.XmlTextReader
Dim sXML As String
Dim emailName As String
'Dim strReusableCookies As String

Try
' Initialize variables.
strUserName = "user1"
strPassword = "pass1"
strDomain = "email.int"
strRootURI = "http://ex01/Exchange/user1/Inbox"

strQuery = "<?xml version=""1.0""?>" & _
"<D:searchrequest xmlns:D = ""DAV:"" >" & _
"<D:sql>SELECT ""dav:href"",""dav:urn:schemas:httpmail:fromemail" " FROM scope('shallow traversal of """ & _
strRootURI & """ ')"


strQuery = strQuery & " WHERE ""urn:schemas:httpmail:fromemail"" = 'cp@cp.com' and ""urn:schemas:httpmail:read""=true ORDER BY ""urn:schemas:httpmail:datereceived"" DESC"
strQuery = strQuery & "</D:sql></D:searchrequest>"

' Create a new CredentialCache object and fill it with the network
' credentials required to access the server.

MyCredentialCache = New System.Net.CredentialCache



MyCredentialCache.Add(New System.Uri(strRootURI), _
"Basic", _
New System.Net.NetworkCredential(strUserName, strPassword, strDomain) _
)

' Create the SEARCH HttpWebRequest object.
Request = CType(System.Net.WebRequest.Create(strRootURI), _
System.Net.HttpWebRequest)

Request.PreAuthenticate = True

' Add the network credentials to the request.
Request.Credentials = MyCredentialCache

Request.KeepAlive = False
Request.Headers.Set("Pragma", "no-cache")
Request.Headers.Set("Translate", "f")
' Set the Content Type header.
Request.ContentType = "text/xml"
Request.Timeout = 300000

' Specify the SEARCH method.
Request.Method = "SEARCH"

' Encode the body using UTF-8.
bytes = System.Text.Encoding.UTF8.GetBytes(strQuery)

' Set the content header length. This must be
' done before writing data to the request stream.
Request.ContentLength = bytes.Length

' Get a reference to the request stream.
RequestStream = Request.GetRequestStream()

' Write the message body to the request stream.
RequestStream.Write(bytes, 0, bytes.Length)

' Close the Stream object to release the connection
' for further use.
RequestStream.Close()




' Send the SEARCH method request and get the
' response from the server.
Response = CType(Request.GetResponse(), System.Net.HttpWebResponse)

' Get the XML response stream.
ResponseStream = Response.GetResponseStream()

' Create the XmlTextReader object from the XML
' response stream.
XmlReader = New System.Xml.XmlTextReader(ResponseStream)

' Read through the XML response, node by node.

While (XmlReader.Read())

XmlReader.GetAttribute("a:href")

' Look for the opening DAV:href node. The DAV: namespace is
' typically assigned the a: prefix in the XML response body.

If XmlReader.Name = "a:href" Then

' Advance the reader to the text node.
XmlReader.Read()


' Display the value of the DAV:href text node.
emailName = XmlReader.Value
Console.WriteLine("Email is : " & emailName)
' Console.WriteLine("Email:" & emailName)


sXML = GetAttachmentsListXML(emailName, strUserName, strPassword)

'Console.WriteLine(sXML)


Dim xmldoc As New Xml.XmlDocument
Dim shref As String
Dim fname As String

xmldoc.LoadXml(sXML)
xmldoc.PreserveWhitespace = False
shref = xmldoc.GetElementsByTagName("a:href").Item(0).Inne rXml
fname = xmldoc.GetElementsByTagName("f:cn").Item(0).InnerX ml

' Console.WriteLine("File Name is : " & fname)
' Console.WriteLine("filePath is : " & shref)


Dim instance As New System.Net.WebClient

DownloadAtt(shref, fname)



' Advance the reader to the closing DAV:href node.
XmlReader.Read()
End If
End While


Console.ReadLine()
' Clean up.
XmlReader.Close()
ResponseStream.Close()
Response.Close()

Catch ex As Exception

' Catch any exceptions. Any error codes from the
' SEARCH method requests on the server will be caught
' here, also.
Console.WriteLine(ex.Message)
Console.Read()
End Try

End Sub

Public Function GetAttachmentsListXML(ByVal sHREF As String, ByVal sUserName As String, ByVal sPassword As String) As Object

Dim HttpWebRequest As MSXML2.XMLHTTP30

HttpWebRequest = New MSXML2.XMLHTTP30
With HttpWebRequest
.open("X-MS-ENUMATTS", sHREF, False, sUserName, sPassword)
.setRequestHeader("Content-type:", "text/xml")
.setRequestHeader("Depth", "1,noroot")
.send()
GetAttachmentsListXML = HttpWebRequest.responseText
End With
HttpWebRequest = Nothing

End Function

Public Sub DownloadAtt(ByVal remoteUri As String, ByVal fileName As String)

Try

Dim myStringWebResource As String = Nothing
' Create a new WebClient instance.
Dim myWebClient As New System.Net.WebClient()
' Concatenate the domain with the Web resource filename. Because DownloadFile
'requires a fully qualified resource name, concatenate the domain with the Web resource file name.
myStringWebResource = remoteUri
Console.WriteLine(myStringWebResource)
Console.WriteLine(fileName)
Console.WriteLine("Downloading File ""{0}"" from ""{1}"" ......." + ControlChars.Cr + ControlChars.Cr, fileName, myStringWebResource)
' The DownloadFile() method downloads the Web resource and saves it into the current file-system folder.
myWebClient.DownloadFile(myStringWebResource, fileName)
Console.WriteLine("Successfully Downloaded file ""{0}"" from ""{1}""", fileName, myStringWebResource)
Console.WriteLine((ControlChars.Cr + "Downloaded file saved in the following file system folder:" + ControlChars.Cr + ControlChars.Tab))
Catch ex As Exception
Console.WriteLine("")
Console.WriteLine(ex)
Console.WriteLine("")
End Try

End Sub


End Module
Sep 11 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.