Thursday, March 2, 2017

C# code to connect outlook from EWS web service

 

-Connect to EWS web service

-Get All unread email from today’s date with Email Parameter

-Get the attachment in Email and save that to local project folder

               

           bool MoreItems = true;
           int offset = 0;
           int pageSize = 1000;
           string BrandName = String.Empty;
           DateTime dateStart = DateTime.Today;
           ExchangeService Service = new ExchangeService();
           sbErrorLog.Append("Setting Web Service Parameter");
           sbErrorLog.AppendLine(); 
           Service.Url = new Uri(“Service URL”);
           sbErrorLog.Append("Web Service URL " + Service.Url.ToString());
           sbErrorLog.AppendLine(); 
           //Set service credentials. This will be the service account. 
           //.  Use the email address
           ExchangeCredentials credentials = new WebCredentials(“Account Name”,Account Password);
           Service.Credentials = credentials;
           // Setting Web Service Credentials
           //WebService Impersonating
          //Setting Up Web Service Certificate");
          Service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, “SMTP Email Address”);
           System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
           //Bind the service object to the Inbox
           //Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
           //Defined search filter for unread messages
           SearchFilter.ContainsSubstring SubjectFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Test Email Read with attachment", ContainmentMode.Substring, ComparisonMode.IgnoreCase);
           SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.LastModifiedTime, dateStart);
           SearchFilter unreadFilter =  new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);

           SearchFilter.SearchFilterCollection searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
           // Setting Up Web Service Filter
          // Filter 1 – Greater Then today’s date and Only unread item
           searchFilterCollection.Add(greaterthanfilter);
           searchFilterCollection.Add(unreadFilter);
           //searchFilterCollection.Add(SubjectFilter);
           //Loop through the items and do whatever is required
           while (MoreItems)
           {
               try
               {
                   string fileLocation = String.Empty;
                   ItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);
                   FindItemsResults<Item> findResults = Service.FindItems(WellKnownFolderName.Inbox, searchFilterCollection, view);
                   Service.LoadPropertiesForItems(findResults, new PropertySet(ItemSchema.DisplayTo, ItemSchema.Body, ItemSchema.LastModifiedName, ItemSchema.Subject, ItemSchema.Attachments));
                   foreach (Item item in findResults)
                   {
                       try
                       {
                           string Body = (item as EmailMessage).Body.ToString();
                           foreach (Microsoft.Exchange.WebServices.Data.Attachment attachment in (item as EmailMessage).Attachments)
                           {
                               if (attachment is FileAttachment)
                               {

                                   FileAttachment fileAttachment = attachment as FileAttachment;

                                   fileLocation = Directory.GetCurrentDirectory() + "\\Files\\" + fileAttachment.Name;
                                  //Get File Location
                                fileAttachment.Load(Directory.GetCurrentDirectory() + "\\Files\\" + fileAttachment.Name);
                                  }
                               else // Attachment is an item attachment.
                               {
                                   ItemAttachment itemAttachment = attachment as ItemAttachment;

                                   // Load attachment into memory and write out the subject.
                                   // This does not save the file like it does with a file attachment.
                                   // This call results in a GetAttachment call to EWS.
                                   itemAttachment.Load();

                                   sbErrorLog.Append("Item attachment name: " + itemAttachment.Name);
                                   sbErrorLog.AppendLine(); 
                               }
                           }

                                                
                       }
                       catch (Exception ex)
                       {
                           sbErrorLog.Append(ex.Message);
                      
                       }
                   }
                   if (!findResults.MoreAvailable)
                       MoreItems = false;
                   else
                   {
                       offset += findResults.Items.Count;
                   }
               }
               catch (Exception ex) {
                   sbErrorLog.Append(ex.Message);
               }
           }

No comments:

Post a Comment