473,387 Members | 1,540 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

exchange + attachments

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
3 2365
kenobewan
4,871 Expert 4TB
Here is a thread that may help:
WebDAV download attachments

Hint: try using the site search :).
Aug 28 '07 #2
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
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

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

Similar topics

1
by: unemotionalhumanoid | last post by:
I am going to write an application in c# that downloads email from an Exchange server and processes the attachments to the email. What is the best way of downloading the email and getting access to...
0
by: Chris | last post by:
I am trying to solve the following problem using c#: One of our customers sends orders using mail attachments. When these attachments arrive at their designated mail account on our exchange...
0
by: fish | last post by:
Hi, I have a VB.net application that will save attachments to a directory on my local pc. I need to run this component on our exchange 2003 server and also save the attachments to a local DIR. ...
7
by: Wiebe Tijsma | last post by:
Hi, I'm using C# + webDAV to create a draft message to be sent in a user's Drafts folder. I can create the message successfully, however when I open the message in outlook, it doesn't show...
1
by: netLynx | last post by:
Hi, I am rewriting code from VB6 using MAPI into VB.NET I need to read an attachment off an email on an Exchange Server. In the old VB6 (not written by me) they restrict the Messages.type to...
4
by: KDawg44 | last post by:
Hi, I am frustrated with my users who send large files around the office instead of using the network shares. For instance, this is one of many emails I have sent around: "If you take the...
5
by: =?Utf-8?B?RGF2aWRF?= | last post by:
Hi, I have to write an application that run once a day that can read all new mails on an exchange special inbox. Then I have to get the subject,attachments,date etc from each email . How can I...
2
by: Salad | last post by:
In A2003 one can create a linked table using File/GetExternalData/Link/Exchange(). It's a nice feature but by and large fairly useless if I am reading the table structure correctly. The From &...
1
by: =?Utf-8?B?SmVzc2ljYQ==?= | last post by:
Hello All, If an application has to be developed in C# which enables the users over a WAN to exchange messages (not real time chat but e-mail like), what mechanism would be the best to exchange...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.