none
By using Exchange server Web service Reading the Inbox file And insert in SQL server Database RRS feed

  • Question

  • Hi,

        I just want to create a Console application and shedule it Fo reading all the mail from Inbox of Exchange server By using ExchangeWeb service (It 2007 sp1 exchange server running).

    I have create application but did not reached my gole .Any help please with example will be great.

    thanks

     

    Friday, March 4, 2011 4:10 PM

Answers

  • Run your code in a debugger and look at the objects that are returned (allways try this) eg you should just be able to cast like

     

    if (inboxItem is MessageType)
    {
      if (((MessageType)inboxItem).From.Item.EmailAddress != null)
        {
          Console.WriteLine((MessageType)inboxItem).From.Item.EmailAddress.ToString());
    
    	}
    }
    
    Cheers
    Glen
    • Marked as answer by santosh jha Monday, March 14, 2011 8:32 AM
    Monday, March 14, 2011 6:37 AM

All replies

  • Hi,

    Any help !

    Is this possible or not . Or I have posted the question in wrong Forum.

    Please suggest me.

    Thanks

    Saturday, March 5, 2011 11:44 AM
  • Yes its possible to read messages from the Inbox maybe one example of using EWS and SQL that might be helpful is http://msdn.microsoft.com/en-us/library/bb508823.aspx

    One suggestion is you should read the forum guide http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/77c07b69-eea6-43ab-9225-4b384cecfc9d and then ask a specific question in regards to what specifically your having a problem with. 

    Cheers
    Glen

    Monday, March 7, 2011 1:49 AM
  • Hi,

    Thanks for Ur reply .

    I have done some work to get the mail but I am not able to Sender mail address .

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.SqlClient;
    using System.Net.Security;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;
    using Microsoft.Exchange.WebServices.Data;
    using System.Net;
    using System.IO;
    using System.Globalization;
    using ExtractEmail.com.XXX.YYYY;
    using System.Data;
    using System.Configuration;
    
    namespace ExtractEmail
    {
      class Program
      {
        SqlConnection Con = new SqlConnection(ConfigurationSettings.AppSettings["Con"].ToString());
        static void Main(string[] args)
        {
          Program p = new Program();
          DataTable DTEmail = p.CreateDataTable();
          //
          ServicePointManager.ServerCertificateValidationCallback =
          delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
          {
            // trust any certificate
            return true;
          };
    
          // First, set up the binding to Exchange Web Services.
          ExchangeServiceBinding binding = new ExchangeServiceBinding();
          binding.Credentials = new NetworkCredential("aaaa@vvv.com", "****", "");
          binding.Url = @"https://sss.vvv.com/EWS/Exchange.asmx";
          
    
    
          //
          // Next, call FindItem for the Inbox folder.
          // Form the FindItem request.
          FindItemType findItemRequest = new FindItemType();
          findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
          //
          // Define which item properties are returned in the response.
          // We only need the ItemIds.
          ItemResponseShapeType itemProperties = new ItemResponseShapeType();
          itemProperties.BaseShape = DefaultShapeNamesType.IdOnly;
          //
          // Add the properties shape to request.
          findItemRequest.ItemShape = itemProperties;
          
          // Identify which folders to search to find items.
          DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[2];
          folderIDArray[0] = new DistinguishedFolderIdType();
          folderIDArray[0].Id = DistinguishedFolderIdNameType.inbox;
          //
          // Add folders to the request.
          findItemRequest.ParentFolderIds = folderIDArray;
          //
          // Send the request and get the response.
          FindItemResponseType findItemResponse = binding.FindItem(findItemRequest);
          // Next, enumerate through the Items returned by FindItem.
    
          foreach (FindItemResponseMessageType responseMessage in findItemResponse.ResponseMessages.Items)
          {
            if (responseMessage.ResponseClass == ResponseClassType.Success)
            {
              ArrayOfRealItemsType mailboxItems =(ArrayOfRealItemsType)responseMessage.RootFolder.Item;
    
              for (int itemCount = 0; itemCount < mailboxItems.Items.Length; itemCount++)
              {
                ItemType inboxItem = mailboxItems.Items[itemCount];
                // Call GetItem on each ItemId to retrieve the 
                // item's Body property and any AttachmentIds.
                 // Form the GetItem request.
                GetItemType getItemRequest = new GetItemType();
    
                getItemRequest.ItemShape =new ItemResponseShapeType();
                // AllProperties on a GetItem request WILL return 
                // the message body.
                getItemRequest.ItemShape.BaseShape =  DefaultShapeNamesType.AllProperties;
    
                getItemRequest.ItemIds = new ItemIdType[1];
                getItemRequest.ItemIds[0] = (BaseItemIdType)inboxItem.ItemId;
    
                GetItemResponseType getItemResponse = binding.GetItem(getItemRequest);
    
                // We only passed in one ItemId to the GetItem
                // request. Therefore, we can assume that
                // we got at most one Item back.
                ItemInfoResponseMessageType getItemResponseMessage = getItemResponse.ResponseMessages.Items[0] as ItemInfoResponseMessageType;
                if (getItemResponseMessage != null)
                {
                  if (getItemResponseMessage.ResponseClass == ResponseClassType.Success && getItemResponseMessage.Items.Items != null && getItemResponseMessage.Items.Items.Length > 0)
                  {
                    
                    inboxItem = getItemResponseMessage.Items.Items[0];
                    //inboxItem.Body.
                                   
                    DataRow DR = DTEmail.NewRow();
                    DR["EMailBody"] = inboxItem.Body.Value.ToString();
                    DR["MailIdTo"] = inboxItem.DisplayTo.ToString();
                    DR["MailIdFrom"] = "";                DR["MailIdSubject"] = inboxItem.Subject.ToString();
                    DR["MailIdInbox"] = inboxItem.ItemId.Id;
                    DR["EmailCreatedDate"] = inboxItem.DateTimeCreated;
    
                    DTEmail.Rows.Add(DR);
                  }
                  else
                  {
                    return;
                  }
                }
                else
                {
                  return;
                }
    
                // Now the message Body is there.
               //  BodyType messageBody = inboxItem.Body;
                //
                // You now have the mailbox item's Body property
                // and you can use it as needed.
                //
                // Check for attachments.
                if (inboxItem.HasAttachments)
                {
                  AttachmentType[] attachments = inboxItem.Attachments;
                  //
                  // Enumerate through the attachments.
                  for (int attachmentCount = 0; attachmentCount < attachments.Length; attachmentCount++)
                  {
                    // Form the GetAttachment request.
                    GetAttachmentType getAttachmentRequest = new GetAttachmentType();
                    //
                    // Add the attachment to retrieve.
                    RequestAttachmentIdType[] attachmentIDArray = new RequestAttachmentIdType[1];
                    attachmentIDArray[0] = new RequestAttachmentIdType();
                    attachmentIDArray[0].Id = attachments[attachmentCount].AttachmentId.Id;
                    getAttachmentRequest.AttachmentIds = attachmentIDArray;
                    //
                    // Make the GetAttachment request.
                    GetAttachmentResponseType getAttachmentResponse = binding.GetAttachment(getAttachmentRequest);
                    //
                    // We then parse through the 
                    // GetAttachment response to get the 
                    //attachment object itself
                    //
                    // We only passed in one AttachmentId.
                    // Therefore, we can assume that we
                    // got at most one attachment back.
                    AttachmentInfoResponseMessageType
                                     attachmentResponseMessage =
                                getAttachmentResponse.ResponseMessages.Items[0]
                                     as AttachmentInfoResponseMessageType;
                    if (attachmentResponseMessage != null)
                    {
                      if
                                    (attachmentResponseMessage.ResponseClass
                                    == ResponseClassType.Success &&
                                    attachmentResponseMessage.Attachments !=
                                    null &&
                                    attachmentResponseMessage.Attachments.Length
                                    > 0)
                      {
                        AttachmentType attachment =
                                       attachmentResponseMessage.Attachments[0];
                      }
                      else
                      {
                        return;
                      }
                    }
                    else
                    {
                      return;
                    }
    
                  }
                }
              }
            }
          }
    
          p.InsertEmail(DTEmail);
        }
    
    
        public void InsertEmail(DataTable Dt)
        {
          SqlBulkCopy SB = new SqlBulkCopy(Con);
          SB.BulkCopyTimeout = 0;
          SB.DestinationTableName = "ExchangeEmail";
          Con.Open();
          SB.WriteToServer(Dt);
          Con.Close();
    
        }
        public DataTable CreateDataTable()
        {
          DataTable Dt = new DataTable();
          DataColumn Dc = new DataColumn("EMailId",typeof(int));
          Dc.AutoIncrement = true;
          Dc.AutoIncrementSeed = 1;
          Dc.AutoIncrementStep = 1;
          Dt.Columns.Add(Dc);
    
          Dc = new DataColumn("EMailBody", typeof(string));
          Dt.Columns.Add(Dc);
    
          Dc = new DataColumn("MailIdTo", typeof(string));
          Dt.Columns.Add(Dc);
    
          Dc = new DataColumn("MailIdFrom", typeof(string));
          Dt.Columns.Add(Dc);
          Dc = new DataColumn("EmailCreatedDate", typeof(DateTime));
          Dt.Columns.Add(Dc);
    
    
          Dc = new DataColumn("MailIdInbox", typeof(string));
          Dt.Columns.Add(Dc);
    
          Dc = new DataColumn("MailIdSubject", typeof(string));
          Dt.Columns.Add(Dc);
          return Dt;
        }
      }
    
      }
    
    
    
    Friday, March 11, 2011 8:49 AM
  • Thanks Glen for your reply.

    I have Implemented the following code to get Mail body and other properties

     inboxItem = getItemResponseMessage.Items.Items[0];
                    //inboxItem.Body.
                                  
                    DataRow DR = DTEmail.NewRow();
                    DR["EMailBody"] = inboxItem.Body.Value.ToString();
                    DR["MailIdTo"] = inboxItem.DisplayTo.ToString();
                    DR["MailIdFrom"] = "";                DR["MailIdSubject"] = inboxItem.Subject.ToString();
                    DR["MailIdInbox"] = inboxItem.ItemId.Id;
                    DR["EmailCreatedDate"] = inboxItem.DateTimeCreated;

                    DTEmail.Rows.Add(DR);

    Now How can I implement The messageType object with each mail to get their FROM email id Or We can't relate both things means Getting FROM mail Id is different thing and Fetching Mail body is different Then how we can Relate both ...

    Please suggest some code. and I am also not getting any Intellicence for function in web service So am unable to understand. Any Help for this also.

    And last one some link for documentation of web service .

    Thanks

    Monday, March 14, 2011 5:59 AM
  • Run your code in a debugger and look at the objects that are returned (allways try this) eg you should just be able to cast like

     

    if (inboxItem is MessageType)
    {
      if (((MessageType)inboxItem).From.Item.EmailAddress != null)
        {
          Console.WriteLine((MessageType)inboxItem).From.Item.EmailAddress.ToString());
    
    	}
    }
    
    Cheers
    Glen
    • Marked as answer by santosh jha Monday, March 14, 2011 8:32 AM
    Monday, March 14, 2011 6:37 AM
  • thanks Glen It works!

    Any help for getting Intellicence for function in web service as

    I have to do more work on this

    thanks

     

    Monday, March 14, 2011 8:34 AM