save attachment from email into database using exchange web service api RRS feed

  • Question

  • I am trying to save attachements from email into database. I want to know what I am doing wrong.

    Here is my code :-

     Public Shared Function GetEmailByID(MessageID As String) As Email
          Dim email As New Email
          Dim toAdressList As String = String.Empty
          Dim service As ExchangeService = GetBinding()
          Dim view As ItemView = New ItemView(1)
          Dim msgItemID As ItemId = New ItemId(MessageID)
          Dim item1 As Item = Item.Bind(service, msgItemID, PropertySet.FirstClassProperties)
          Dim emailMsg As EmailMessage = DirectCast(item1, EmailMessage)
          email.EmailID = emailMsg.Id.ToString
          email.Sender = emailMsg.Sender.ToString
          For Each emailAddrs In emailMsg.ToRecipients
            toAdressList = toAdressList + emailAddrs.ToString + ","
          email.ToAddress = toAdressList.Remove(toAdressList.Count - 1)
          email.DateReceived = emailMsg.DateTimeReceived
          email.Subject = emailMsg.Subject
          email.Body = emailMsg.Body
          email.HasAttachements = emailMsg.HasAttachments
          If emailMsg.HasAttachments = True Then
            Dim emailAttchments As New List(Of Email.EmailAttachment)
            Dim emailAttchment As New Email.EmailAttachment
            For Each emailAtt In emailMsg.Attachments
              Dim fa As FileAttachment = DirectCast(emailAtt, FileAttachment)
              emailAttchment.attName = emailAtt.Name
              'emailAttchment.attSize = emailAtt.Size
              emailAttchment.attContentType = emailAtt.ContentType
              emailAttchment.attBody = GetAttachmentBody(fa)
            email.Attachments = emailAttchments
          End If
          Return email
        Catch ex As Exception
          Return Nothing
        End Try
      End Function
     Private Shared Function GetAttachmentBody(emailAtt As FileAttachment) As String
        Dim reader As StreamReader = Nothing
        Dim emailAttBody As String = String.Empty
        Dim stream As MemoryStream = New MemoryStream
          stream.Seek(0, SeekOrigin.Begin)
          reader = New StreamReader(stream)
          emailAttBody = reader.ReadToEnd
          Return emailAttBody
        Catch ex As Exception
          Return ""
          If (IsNothing(reader) = False) Then
          End If
        End Try


    Friday, July 29, 2011 6:17 PM

All replies

  • Hi ,

    after the HasAttachments try calling the below method



    Suppose you know the Item.Id.UniqueId which is a string and store it in Myid string variable
     Dim MyKey As New ItemId(Myid)
    Dim MyEmailMessage As EmailMessage
     Dim psPropset As New PropertySet()
     psPropset.BasePropertySet = BasePropertySet.FirstClassProperties
     <strong>psPropset.Add(ItemSchema.Attachments) 'this is very important . If you don't add this the hasattachments doesn't work
    psPropset.RequestedBodyType = BodyType.Text
     MyEmailMessage = EmailMessage.Bind(Me.MyExchangeService, MyKey, psPropset)
    if MyemailMessage.HasAttachments then
     end if

     Private Function ProcessAttachments(ByVal MyLocalMessage As EmailMessage) As Int16
    Try ' Iterate through the attachments collection and load each attachment. For Each attachment As Attachment In MyLocalMessage.Attachments Dim strFilename As String = "" If TypeOf attachment Is FileAttachment Then Dim fileAttachment As FileAttachment = TryCast(attachment, FileAttachment) strFilename = fileAttachment.Name If strFilename.Length > 240 Then If strFilename.IndexOf(".html") <= 0 Then Dim extension As String = GetTheExtension(strFilename) strFilename = "Attachment" & "." & extension Else strFilename = "Attachment.html" End If End If Dim MyOriginalFile As String strFilename = ReplaceControlCharsForFiles(strFilename) MyOriginalFile = strFilename Dim i As Int32 = 0 Do i = i + 1 If DetermineIfFileExists(AttachmentDir & "\" & strFilename) = False Then Exit Do Else strFilename = Convert.ToString(i) & "_" & MyOriginalFile End If Loop Until False ' Stream attachment contents into a file. Dim theStream As New FileStream(AttachmentDir & "\" & strFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite) fileAttachment.Load(theStream) theStream.Close() theStream.Dispose() Me.AttachmentPaths = AttachmentDir & "\" & strFilename Else ' Attachment is an item attachment. ' Load attachment into memory and write out the subject. Dim itemAttachment As ItemAttachment = TryCast(attachment, ItemAttachment) itemAttachment.Load() Dim MySubject As String Dim MyBody As String Dim FinalString As String MySubject = itemAttachment.Item.Subject MyBody = itemAttachment.Item.Body FinalString = MySubject & vbCrLf & MyBody strFilename = "BB_Attachment.eml" Dim MyOriginalFile As String MyOriginalFile = strFilename Dim i As Int32 = 0 Do i = i + 1 If DetermineIfFileExists(AttachmentDir & "\" & strFilename) = False Then Exit Do Else strFilename = Convert.ToString(i) & "_" & MyOriginalFile End If Loop Until False Dim enc As System.Text.Encoding = System.Text.Encoding.ASCII Dim _ResponseBody As Byte() = enc.GetBytes(FinalString) My.Computer.FileSystem.WriteAllBytes(AttachmentDir & "\" & strFilename, _ResponseBody, False) Me.AttachmentPaths = AttachmentDir & "\" & strFilename End If Next Catch ex As Exception ErrorCode = -1 Me.SetErrorMessage(ex.Message) Throw ex End Try Return 0 End Function Private Function DetermineIfFileExists(ByVal sfilename As String) As Boolean Dim fFile As New FileInfo(sfilename) If Not fFile.Exists Then Return False End If Return True End Function <br/>Private Function GetTheExtension(ByVal strfilename As String) As String<br/> Dim dot As Integer = strfilename.LastIndexOf(".")<br/> Return strfilename.Substring(dot + 1)<br/> End Function


    For me the above code worked.

    Of course you can modify the processattachments method to your own needs because I'm doing some stuff for my app.


    thank you


    Thursday, August 4, 2011 11:15 AM