using System; using System.Collections.Generic; using System.Linq; using System.Text; using EWS_test.CopyService; using System.IO; using Microsoft.Exchange; using Microsoft.Exchange.WebServices; using Microsoft.Exchange.WebServices.Data; using Microsoft.Exchange.WebServices.Autodiscover; using System.Data; namespace EWS_test { class Program { static void Main(string[] args) { // Step 1: Get handle to Exchange Services ExchangeService ews = GetExchangeService("https://[Your Exchange OWA Url]/EWS/Exchange.asmx"); // Step 2: Load first 10 matching inbox entries into a table DataTable dtInbox = GetInbox(ews, 10, ""); // Step 3: Loop through table of inbox messages, // uploading each email, to a SharePoint list // and deleting the original from inbox int cnt = 1; foreach (DataRow drMessage in dtInbox.Rows) { // Step 4: Upload copy of email in .EML form to SharePoint EmailMessage message = GetMessage(ews, drMessage["MsgId"].ToString()); UploadFile(message, "http://sptest/sites/ewstest", "Shared Documents", cnt); Console.WriteLine(cnt.ToString() + ": " + drMessage["Subject"].ToString() + " (" + cnt.ToString() + ")"); cnt++; // Step 5: Delete the original email message.Delete(DeleteMode.MoveToDeletedItems); } Console.WriteLine(); Console.WriteLine("Press any key to continue..."); Console.Read(); } // Remove any special characters that may cause // problems for SharePoint from the subject line static string FixUpFileName(string subject) { // Note: this is a partial list of potentially offending characters, // a more robust implementation will test for all such string[] fileNameSegments = subject.Split(new char[] { ':', ';', '\'', '"', '&', '/', '?', '|'}); string fileName = ""; for (int i = 0; i < fileNameSegments.Length; i++) { if (fileName != "") fileName += "_"; fileName += fileNameSegments[i]; } return fileName + ".eml"; } // Get a handle to current users Exchange folders static ExchangeService GetExchangeService(string url) { ExchangeService ews = new ExchangeService(ExchangeVersion.Exchange2010); ews.Url = new Uri(url); ews.Credentials = (WebCredentials)System.Net.CredentialCache.DefaultNetworkCredentials; return ews; } // Return collection of field information to be // uploaded along with the email contents static FieldInformation[] GetFieldInformation(EmailMessage message) { // Assume the following fields exist in the target list: // // Subject // From // FromAddress // To // ToAddress // Received // var subject = new FieldInformation { DisplayName = "Subject", InternalName = "Title", Type = FieldType.Text, Value = message.Subject }; FieldInformation from = new FieldInformation { DisplayName = "From", InternalName = "From", Type = FieldType.Text, Value = message.From.Name }; FieldInformation fromAddress = new FieldInformation { DisplayName = "FromAddress", InternalName = "FromAddress", Type = FieldType.Text, Value = message.From.Address }; FieldInformation to = new FieldInformation { DisplayName = "To", InternalName = "To", Type = FieldType.Text, Value = GetReceipientNames(message) }; FieldInformation toAddress = new FieldInformation { DisplayName = "ToAddress", InternalName = "ToAddress", Type = FieldType.Text, Value = GetReceipientAddresses(message) }; // Date value must be reformatted so it can be // understood by SharePoint FieldInformation received = new FieldInformation { DisplayName = "Received", InternalName = "Received", Type = FieldType.DateTime, Value = string.Format("{0}-{1}-{2}T{3}:{4}:{5}Z", message.DateTimeReceived.ToUniversalTime().Year.ToString(), message.DateTimeReceived.ToUniversalTime().Month.ToString().PadLeft(2, '0'), message.DateTimeReceived.ToUniversalTime().Day.ToString().PadLeft(2, '0'), message.DateTimeReceived.ToUniversalTime().Hour.ToString().PadLeft(2, '0'), message.DateTimeReceived.ToUniversalTime().Minute.ToString().PadLeft(2, '0'), message.DateTimeReceived.ToUniversalTime().Second.ToString().PadLeft(2, '0')) }; FieldInformation[] info = { subject, from, fromAddress, received, to, toAddress }; return info; } // Read an inbox and return a DataTable object // containing the basic information for each message static DataTable GetInbox(ExchangeService ews, int maxMsgCount, string searchFor) { // Create table to hold inbox items DataTable dtInbox = new DataTable("Inbox"); dtInbox.Columns.Add("From"); dtInbox.Columns.Add("FromAddress"); dtInbox.Columns.Add("To"); dtInbox.Columns.Add("ToAddresses"); dtInbox.Columns.Add("Subject"); dtInbox.Columns.Add("MsgId"); dtInbox.Columns.Add("MsgClass"); DataColumn dc = new DataColumn("DateTimeReceived", typeof(DateTime)); dtInbox.Columns.Add(dc); dtInbox.Columns.Add("Id"); // Add first items in inbox to dataset ItemView itemView = new ItemView(maxMsgCount); itemView.PropertySet = BasePropertySet.FirstClassProperties; int cnt = 0; // Create the search filter that finds emails with // the "searchFor" string in the subject line SearchFilter.SearchFilterCollection searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.Or); if (searchFor != "") { searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, searchFor)); } else { // If an empty string was passed in for the search filter, // setting the search filter collection to null will result // in a match for all emails searchFilterCollection = null; } foreach (EmailMessage message in ews.FindItems(WellKnownFolderName.Inbox, searchFilterCollection, itemView)) { message.Load(); DataRow drMessage = dtInbox.NewRow(); drMessage["From"] = message.From.Name; drMessage["FromAddress"] = message.From.Address; drMessage["To"] = GetReceipientNames(message); drMessage["ToAddresses"] = GetReceipientAddresses(message); drMessage["Subject"] = message.Subject; drMessage["MsgId"] = message.Id.ToString(); drMessage["DateTimeReceived"] = message.DateTimeReceived.ToString(); drMessage["Id"] = cnt.ToString(); drMessage["MsgClass"] = message.ItemClass; dtInbox.Rows.Add(drMessage); dtInbox.AcceptChanges(); cnt++; } return dtInbox; } // Return an email message object given its uinque // message id static EmailMessage GetMessage(ExchangeService ews, string id) { try { ItemId msgId = new ItemId(id); EmailMessage message = EmailMessage.Bind(ews, msgId, BasePropertySet.FirstClassProperties); return message; } catch { return null; } } // Return a byte array containing email contents static byte[] GetMessageBytes(EmailMessage message) { message.Load(new PropertySet(ItemSchema.MimeContent)); MimeContent mimeContent = message.MimeContent; byte[] contents = mimeContent.Content; return contents; } // Return a semicolon-delimited list of // email recipient addresses static string GetReceipientAddresses(EmailMessage message) { string addresses = ""; for (int i = 0; i < message.ToRecipients.Count; i++) { if (addresses.Length > 0) addresses += "; "; addresses += message.ToRecipients[i].Address; } return addresses; } // Return a semicolon-delimited list of // email recipient names static string GetReceipientNames(EmailMessage message) { string names = ""; for (int i = 0; i < message.ToRecipients.Count; i++) { if (names.Length > 0) names += "; "; names += message.ToRecipients[i].Name; } return names; } // Upload a message to SharePoint library private static uint UploadFile(EmailMessage message, string siteUrl, string libraryName, int cnt) { // Get handle to SharePoint copy service CopyService.Copy csv = new EWS_test.CopyService.Copy(); csv.Credentials = System.Net.CredentialCache.DefaultCredentials; csv.Url = siteUrl + "/_vti_bin/copy.asmx"; // Construct a file name using the message subject string fileName = FixUpFileName(message.Subject + " (" + cnt.ToString() + ")"); string destinationUrl = siteUrl + "/" + libraryName + "/" + fileName; string[] destinationUrls = { destinationUrl }; // Array containing metadata to be assigned to // uploaded message FieldInformation[] info = GetFieldInformation(message); // Array to receive results of upload var copyResult = new CopyResult(); CopyResult[] copyResults = { copyResult }; // Get message contents byte[] contents = GetMessageBytes(message); // Upload to SharePoint uint result = csv.CopyIntoItems("http://null", destinationUrls, info, contents, out copyResults); return result; } } }