none
Trying to get the FROM address of an email with EWS and VB.Net RRS feed

  • Question

  • This is my 1st attempt to use EWS and it's been going very well but I can't seem to get the FROM address of an email message. I have the list of messages and I can get the body and subject but I don't see the from address anywhere. I'm assuming I 'm missing something simple. Any guidance in the right direction would be greatly appreciated
    Thursday, July 24, 2014 3:23 PM

Answers

  • As long as you are enumerating Email Messages then you just need to cast the to the MessageType class and you should be able to use the From or Sender properties eg

                    strbody = (messages(j).Body.Value).ToString
                    blattachments = messages(j).HasAttachments
                    mid = messages(j).ItemId
                    strsubject = messages(j).Subject.ToString
                    Dim FromAddress As String = ""
                    If (messages(j).GetType() Is GetType(MessageType)) Then
                        Dim EmailObj As MessageType = DirectCast(messages(j), MessageType)
                        FromAddress = EmailObj.From().Item.EmailAddress
                    End If
    Cheers
    Glen

    • Marked as answer by SHIROCZ Thursday, July 31, 2014 12:53 PM
    Monday, July 28, 2014 4:26 AM

All replies

  • What does the code your trying to use look like ? EWS will only return the properties you ask it to return so it really depends what your code looks like

    Rgds
    Glen

    Friday, July 25, 2014 3:51 AM
  • This is some sample code that gets the items from the inbox, checks for attachments and then saves them. I was attempting to use this code to add some of the email items information to a database table. The Body and Subject were readily available from the messages array but I don't see From address here. So it seems I'm not asking for enough information.

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim mid As ItemIdType
            Using exchangeServer As New ExchangeServiceBinding()
    
                ' This portion uses the credentials you provided and 
                ' initiates the connection to the Web Service
                Dim creds As ICredentials = New NetworkCredential(strUsername, strPassword)
                exchangeServer.Credentials = creds
                exchangeServer.Url = strExchAsmx
    
                ' Since this is not a folder search we opt for Shallow Traversal Type
                Dim findItemRequest As New FindItemType()
                findItemRequest.Traversal = ItemQueryTraversalType.Shallow
    
                ' The BaseShape property Gets or Sets the requested 
                ' properties to return in a response
                Dim itemProperties As New ItemResponseShapeType()
                itemProperties.BaseShape = DefaultShapeNamesType.AllProperties
    
                ' Here the item shape property is set, Go To definition on 
                ' FindItemType for more info
                findItemRequest.ItemShape = itemProperties
    
                ' Setup a folder array and define the folder Name and then set the parent 
                ' folder ID Field with it to filter the search to just the inbox. 
                Dim folderIDArray As DistinguishedFolderIdType() = New DistinguishedFolderIdType(0) {}
                folderIDArray(0) = New DistinguishedFolderIdType()
                folderIDArray(0).Id = DistinguishedFolderIdNameType.inbox
                findItemRequest.ParentFolderIds = folderIDArray
    
                ' This block initiates the reading of the messages, 
                ' Declares variables for the folder and items in that folder
                ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf CertificateValidationCallBack)
                Dim findItemResponse As FindItemResponseType = exchangeServer.FindItem(findItemRequest)
                Dim folder As FindItemResponseMessageType = _
                DirectCast(findItemResponse.ResponseMessages.Items(0), FindItemResponseMessageType)
                Dim folderContents As New ArrayOfRealItemsType()
                folderContents = DirectCast(folder.RootFolder.Item, ArrayOfRealItemsType)
                Dim items As ItemType() = folderContents.Items
    
                ' if there are no items in the folder (Inbox) then exit
                If items Is Nothing OrElse items.Count() <= 0 Then
                    MsgBox("No Items Found!")
                    Me.Close()
                    Exit Sub
                End If
    
                ' Get the encoded ids of each item
                Dim itemIds As BaseItemIdType() = New BaseItemIdType(items.Count() - 1) {}
                For i As Integer = 0 To items.Count() - 1
                    itemIds(i) = items(i).ItemId
                Next
    
                ' GetItemType is a class that represents a 
                ' request to get items from a mailbox
                Dim getItemType As New GetItemType()
    
                ' GetItemType variable here is defining the 
                ' items to get in that request
                getItemType.ItemIds = itemIds
                getItemType.ItemShape = New ItemResponseShapeType()
                getItemType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties
                getItemType.ItemShape.BodyType = BodyTypeResponseType.Text
                getItemType.ItemShape.BodyTypeSpecified = True
    
                ' This is the response from the exchange server with a number of messages 
                ' that fit the parameters of the request
                Dim getItemResponse As GetItemResponseType = exchangeServer.GetItem(getItemType)
                Dim messages As ItemType() = New ItemType(getItemResponse.ResponseMessages.Items.Count() - 1) {}
                Dim f As Integer = 0
                Dim j As Integer = 0
                Dim h As Integer = 0
                Dim strbody, strsubject As String
                Dim blattachments As Boolean
                ' Here we loop through each message in that response and 
                ' if we find an attachment we extract it
                For j = 0 To messages.Count() - 1
    
                    'Here inside the loop we set the messages itemtype to 
                    ' a single message in the exchange response
                    messages(j) = DirectCast(getItemResponse.ResponseMessages.Items(j), ItemInfoResponseMessageType).Items.Items(0)
    
    
                    '******************************************************************************************************************
                    strbody = (messages(j).Body.Value).ToString
                    blattachments = messages(j).HasAttachments
                    mid = messages(j).ItemId
                    strsubject = messages(j).Subject.ToString
                    '********************************************************************************************************************
    
                    ' We evaluate the message to see if it has attachments, 
                    ' we have no else portion so on to the next message
                    If (messages(j).HasAttachments = True) Then
                        f = f + 1
    
                        ' In this block we see what is attached and get the resulting 
                        ' attachment id so that we can extract it
                        Dim request As New GetAttachmentType()
                        Dim responseShape As New AttachmentResponseShapeType()
                        responseShape.BodyType = BodyTypeResponseType.Text
                        responseShape.BodyTypeSpecified = True
                        request.AttachmentShape = responseShape
                        Dim ids As RequestAttachmentIdType() = New RequestAttachmentIdType(0) {}
                        ids(0) = New RequestAttachmentIdType()
                        ids(0).Id = Convert.ToString(messages(j).Attachments(0).AttachmentId.Id)
                        request.AttachmentIds = ids
    
                        Try
                            ' Here we request the attachment from the exchange server
                            Dim response As GetAttachmentResponseType = exchangeServer.GetAttachment(request)
                            Dim rmta As ResponseMessageType() = response.ResponseMessages.Items
    
                            ' For each attachment in the request per attachment ID within the single message
                            ' we will get the attachment type and process each accordingly
                            For Each responseMessage As ResponseMessageType In rmta
                                Dim airmt As AttachmentInfoResponseMessageType = TryCast(responseMessage, AttachmentInfoResponseMessageType)
    
                                Dim attachments As AttachmentType() = airmt.Attachments
                                For Each attachment As AttachmentType In attachments
    
                                    ' Based on what the file type is it will be process or converted differently
                                    ' This portion does that.  I have used this with word documents and images.
                                    If TypeOf attachment Is FileAttachmentType Then
                                        Dim TheFileAttachment As FileAttachmentType = DirectCast(attachment, FileAttachmentType)
                                        Using File2Disk As Stream = New FileStream(strAttachPath & "\" & messages(j).Attachments(0).Name, FileMode.Create)
                                            File2Disk.Write(TheFileAttachment.Content, 0, TheFileAttachment.Content.Length)
                                            File2Disk.Flush()
                                            File2Disk.Close()
                                        End Using
                                    Else
                                        Dim TheItemAttachment As ItemType = DirectCast(attachment, ItemAttachmentType).Item
                                        Dim ContentBytes() As Byte = Convert.FromBase64String(TheItemAttachment.MimeContent.Value)
                                        Using Item2Disk As Stream = New FileStream(strAttachPath & "\" & messages(j).Attachments(0).Name + ".eml", FileMode.Create)
                                            Item2Disk.Write(ContentBytes, 0, ContentBytes.Length)
                                            Item2Disk.Flush()
                                            Item2Disk.Close()
                                        End Using
                                    End If
                                    h = h + 1
                                Next
                            Next
                        Catch x As Exception
                            Console.WriteLine(x.Message)
                        End Try
    
                    End If
                    '******************************************************Move Code**************************************************************************************
                    ' Try
                    Dim itemID As New ItemIdType
                    itemID.Id = mid.Id
    
                    'Find the folderId to which we want to move item
                    Dim parentFolder As New DistinguishedFolderIdType
                    parentFolder.Id = DistinguishedFolderIdNameType.root
                    Dim tfTargetFolder As New FolderIdType
                    'Change the name of the folder we are searching for FolderID
                    tfTargetFolder = FindFolder(exchangeServer, parentFolder, "Test")
    
                    Dim newItemID As New ItemIdType
                    'Move am Item based on ItemId and FolderID
                    newItemID = MoveItemtoTest(exchangeServer, itemID.Id, tfTargetFolder)
    
                    '*****************************************************************************************************************************************************
                    '**************************************Create database entry******************************************************************
                    Dim strtrackingnumber
                    Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\Russ\office\TEXT\SALES\After Market\After Market Database\amarket.mdb;User Id=admin;Password=;"
                    Dim cmdupdate As New System.Data.OleDb.OleDbCommand
                    Dim DBConnection As New System.Data.OleDb.OleDbConnection(strConn)
                    Dim strSQL, strSQL1, strSQL2 As String
                    strtrackingnumber = Now.Month.ToString & Now.Day.ToString & Now.Year.ToString & Now.Hour.ToString & Now.Minute.ToString & Now.Second.ToString
                    strSQL1 = "Insert Into [tblAMSQRequest] ([tracking_number],[dtcreated],[request],[ynattachments],[subject])"
                    strSQL2 = "Values ('" & strtrackingnumber & "', #" & Now & "#, '" & strbody & "'," & blattachments & ", '" & strsubject & "')"
                    strSQL = strSQL1 & " " & strSQL2
                    Dim cmd As New System.Data.OleDb.OleDbCommand(strSQL, DBConnection)
                    DBConnection.Open()
                    cmd.ExecuteNonQuery()
                    DBConnection.Close()
                    '******************************************************************************************************************************
                Next
                Me.Close()
            End Using
        End Sub

    Friday, July 25, 2014 11:51 AM
  • As long as you are enumerating Email Messages then you just need to cast the to the MessageType class and you should be able to use the From or Sender properties eg

                    strbody = (messages(j).Body.Value).ToString
                    blattachments = messages(j).HasAttachments
                    mid = messages(j).ItemId
                    strsubject = messages(j).Subject.ToString
                    Dim FromAddress As String = ""
                    If (messages(j).GetType() Is GetType(MessageType)) Then
                        Dim EmailObj As MessageType = DirectCast(messages(j), MessageType)
                        FromAddress = EmailObj.From().Item.EmailAddress
                    End If
    Cheers
    Glen

    • Marked as answer by SHIROCZ Thursday, July 31, 2014 12:53 PM
    Monday, July 28, 2014 4:26 AM
  • Thank You

    That was exactly what I was looking for.

    Thursday, July 31, 2014 12:54 PM