Get mail from folder within Inbox - EWS - c#

I want to access emails in a folder called "ITServiceDesk" in my exchange inbox.
I can access the folder but i cant figure out how to read the mail inside that folder.
I am accessing the folder here:
var view = new FolderView(100);
view.Traversal = FolderTraversal.Deep;
var fileview = new ItemView(100);
var filter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "ITServiceDesk");
// Read 100 mails
foreach (var item in _service.FindFolders(WellKnownFolderName.Inbox, filter, view))
{
MessageBox.Show(item.DisplayName);
foreach (EmailMessage email in _service.FindItems(WellKnownFolderName.Inbox, filter, fileview))
{
email.Load(new PropertySet(EmailMessageSchema.ConversationTopic, ItemSchema.Attachments,
ItemSchema.TextBody));
MessageBox.Show(email.ConversationTopic);
MessageBox.Show(email.TextBody);
}
}
Nothing happens when i get inside the second foreach loop. The message box shows that it can find the folder as the item.displayname is correct.

If you are finding the folder with you code then just call the findItem method on the Folder object that is returned eg
foreach (var Folder in _service.FindFolders(WellKnownFolderName.Inbox, filter, view))
{
MessageBox.Show(Folder.DisplayName);
foreach (EmailMessage email in Folder.FindItems(fileview))
{
email.Load(new PropertySet(EmailMessageSchema.ConversationTopic, ItemSchema.Attachments,
ItemSchema.TextBody));
MessageBox.Show(email.ConversationTopic);
MessageBox.Show(email.TextBody);
}
}

Here is an example from my website:
FindItemsResults<Item> findResults
= service.FindItems(WellKnownFolderName.Inbox, new ItemView( 10 ) );
foreach ( Item item in findResults.Items )
Console.WriteLine( item.Subject );
See C#: Getting All Emails From Exchange using Exchange Web Services

Related

Search attachments from a mailbox using EWS Managed API and C#

I want to search all attachments from a mailbox having certain keywords in their name.I am doing this using C# EWS Managed API(version 2.2).
I am able to access the Item with attachments using Item.HasAttachment:true property and the code is working as expected. But the processing time is very long.
The current process flow is :
1.Get all the folders from a mailbox.
2.For each folder, search items having attchments (using Item.HasAttachment:true searcFilter).
3.Check whether the Attachment name contains the keywords.
I need to know if there is a better and faster way to access attachments in a mailbox/folder using EWS. Instead of checking every mail item, is there a way to apply filter for attachments on folder level?
Below is the code snippet used to fetch the attachemnts by name keyword
SearchFilter searchFilter = new SearchFilter.IsEqualTo(ItemSchema.HasAttachments, true); //SearchFilter for finding item with attachments
FindItemsResults<Item> searchResults = null;
FileAttachment fileAttachmentobj = null;
ItemAttachment itemAttachmentobj = null;
for (var j = 0; j < folder.Count; j++) //Looping for all the folders in a mailbox
{
for (int i = 0; i < strAttachNameKeyword.Length; i++) //Looping for keywords to be searched
{
searchResults = service.FindItems(folder[j].Id, searchFilter, view);
if (searchResults.TotalCount > 0)
{
service.LoadPropertiesForItems(searchResults, new PropertySet(BasePropertySet.IdOnly, ItemSchema.HasAttachments));
foreach (Item item in searchResults) //Processing each item in SearchResults
{
item.Load();
foreach (Attachment attachmentObj in item.Attachments) //for each attachment in an item
{
//attachmentObj.Load();
fileAttachmentobj = attachmentObj as FileAttachment;
itemAttachmentobj = attachmentObj as ItemAttachment;
if (fileAttachmentobj != null && (fileAttachmentobj.Name.Contains(strAttachNameKeyword[i])))
{
//fileAttachmentobj.Load();
Console.WriteLine(fileAttachmentobj.Name);
Console.WriteLine(fileAttachmentobj.Size);
Console.WriteLine(fileAttachmentobj.Id);
}
}
}
}
}
}
I'd suggest you use a QueryString instead of a SearchFilter which means you'll be doing a Content Index search rather the a folder restriction which is much faster. eg
FindItemsResults fiItems = service.FindItems(QueryFolder, "Attachment:blah.pdf", iv);
You can easily test this using the EWSEditor https://github.com/dseph/EwsEditor/releases if you right click a folder->search for items and select the AQS radio button it has a simple interface for AQS/KQL queries

Code to list all permissions for SharePoint Folders

I'm after some C# code to recursively enumerate all the folders in a SharePoint web site and list the permissions applying to them to be run from a Sharepoint client machine. Can anyone provide or point me to an example?
The following code can perform this function on a server using SPSite object ( from https://social.msdn.microsoft.com/Forums/sqlserver/en-US/8c7c5735-039e-4cb9-a2b5-58d70a10793f/get-permissions-group-from-folders-tree-view-on-a-doc-library?forum=sharepointdevelopmentprevious) but I need to run it using SharePoint Client code
public static void getPermissionsOfFolders()
{
using (SPSite site = new SPSite("http://sp"))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.GetList("/Lists/List2");
foreach (SPListItem item in list.Folders)
{
Console.WriteLine("ID: "+item["ID"]+"--"+item.SortType);
if (SPFileSystemObjectType.Folder == item.SortType)
{
SPRoleAssignmentCollection roles = item.RoleAssignments;
foreach (SPRoleAssignment role in roles)
{
Console.WriteLine("~");
Console.WriteLine("Name: "+role.Member.Name);
SPRoleDefinitionBindingCollection bindings = role.RoleDefinitionBindings;
XmlDocument doc = new XmlDocument();
doc.LoadXml(bindings.Xml);
XmlNodeList itemList = doc.DocumentElement.SelectNodes("Role");
foreach (XmlNode currNode in itemList)
{
string s = currNode.Attributes["Name"].Value.ToString();
Console.WriteLine("Permission Level: "+s);
}
}
Console.WriteLine("--------------------------------------");
}
}
}
}
}
Code below fails with exception "Property ListItemAllFields not found" as shown below on clientContext.ExecuteQuery()
private void ListSPPermissions3()
{
string sSite = "http://server2012a/sites/TestDocs/";
using (var clientContext = new ClientContext(sSite))
{
Site site = clientContext.Site;
Web web = clientContext.Web;
List list = web.Lists.GetByTitle("Shared Documents");
clientContext.Load(list.RootFolder.Folders); //load the client object list.RootFolder.Folders
clientContext.ExecuteQuery();
int FolderCount = list.RootFolder.Folders.Count;
foreach (Microsoft.SharePoint.Client.Folder folder in list.RootFolder.Folders)
{
RoleAssignmentCollection roleAssCol = folder.ListItemAllFields.RoleAssignments;
clientContext.Load(roleAssCol);
clientContext.ExecuteQuery(); // Exception property ListItemAllFields not found
foreach (RoleAssignment roleAss in roleAssCol)
{
Console.WriteLine(roleAss.Member.Title);
}
}
}
}
There are at least the following flaws with your example:
The specified example only allows to retrieve folders one level
beneath:
clientContext.Load(list.RootFolder.Folders); //load the client object list.RootFolder.Folders
clientContext.ExecuteQuery();
Role assignments could be retrieved using a single request to the
server (see the below example), hence there is no need to perform
multiple requests to retrieve role assignments per folder.
Folder.ListItemAllFields property is supported only in SharePoint
2013 CSOM API
Having said that i would recommend to consider the following example to enumerate folder permissions:
using (var ctx = new ClientContext(webUri))
{
var list = ctx.Web.Lists.GetByTitle(listTitle);
var items = list.GetItems(CamlQuery.CreateAllFoldersQuery());
ctx.Load(items, icol => icol.Include(i => i.RoleAssignments.Include( ra => ra.Member), i => i.DisplayName ));
ctx.ExecuteQuery();
foreach (var item in items)
{
Console.WriteLine("{0} folder permissions",item.DisplayName);
foreach (var assignment in item.RoleAssignments)
{
Console.WriteLine(assignment.Member.Title);
}
}
}
The error is probably because the SharePoint SDK you are using is pre-SharePoint 2013 CSOM.
Folder.ListItemAllFields
property is available in SharePoint 2013 CSOM
For SharePoint 2010, you have to access folders like list items
ListItem item = context.Web.Lists.GetByTitle("Shared Documents").GetItemById(<item ID>);
and then get the RoleAssignments for the items.

EWS Managed API: Identify deleted email when fetching from "AllItems" folder

I am using EWS managed API with C# to fetch emails from user accounts. I am fetching the emails from "AllItems" folder and getting different email properties such as subject, datetimesent, etc.
"AllItems" folder also contains emails that are deleted and are in "DeletedItems" folder. I would like to identify whether the email is deleted (i.e. it is in "DeletedItems" folder) and if possible, when the email was deleted.
Below is the code I am using. I could not find a property that would identify whether the email is deleted.
FolderView viewFolders = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep, PropertySet = new PropertySet(BasePropertySet.IdOnly) };
ItemView viewEmails = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) };
SearchFilter folderFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "AllItems");
FolderId rootFolderId = new FolderId(WellKnownFolderName.Root);
FindItemsResults<Item> findResults;
FindFoldersResults AllItemsFolder= service.FindFolders(WellKnownFolderName.Root, folderFilter, viewFolders);
if (AllItemsFolder.Count() > 0)//if we have AllItems folder
{
foreach (Folder folder in AllItemsFolder.Folders)
{
ItemView itv = new ItemView(int.MaxValue);
findResults = service.FindItems(folder.Id, itv);
foreach (Item item in findResults)
{
if (item is EmailMessage)
{
MessageBox.Show(item.Subject);
// Show whether the message is in deleted folder and when message was deleted
}
}
}
}
As you state, I don't think there is a property like that for mail items.
I would use the GetFolder operation with the well known folder name "deleteditems" to get the Id of that folder. Then, I would ignore all mail items that has this Id as ParentFolderId.

Get only text of Item from ItemAttachment (EWS Managed API)

Is there a way to remove HTML tags from Item which is from ItemAttachment?
I can get only text from Item. But not from Item which is from ItemAttachment.
Here is my code:
foreach (ItemAttachment itemAttach in item.Attachments.OfType<ItemAttachment>())
{
Console.WriteLine(itemAttach.Name);
itemAttach.Load();
PropertySet propSet = new PropertySet();
propSet.RequestedBodyType = BodyType.Text;
propSet.BasePropertySet = BasePropertySet.FirstClassProperties;
itemAttach.Item.Load(propSet);
Console.WriteLine(itemAttach.Item.Body.Text);
}
It will get this exception
This operation isn't supported on attachments
I tried binding to the exchange service with item ID.
It also gives me some exception!
Please give some advice on how I can do.
Jin,
The exception you are getting has to do with the property set you are creating. I don't see your code for getting the items so I can't determine the exact cause. I was able to get the following code to work on my machine. You should be able to modify it for your needs.
// Return the first ten items.
ItemView view = new ItemView(10);
// Set the query string to only find emails with attachments.
string querystring = "HasAttachments:true Kind:email";
// Find the items in the Inbox.
FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view);
// Loop through the results.
foreach (EmailMessage email in results)
{
// Load the email message with the attachments
email.Load(new PropertySet(EmailMessageSchema.Attachments));
// Loop through the attachments.
foreach (Attachment attachment in email.Attachments)
{
// Only process item attachments.
if (attachment is ItemAttachment)
{
ItemAttachment itemAttachment = attachment as ItemAttachment;
// Load the attachment.
itemAttachment.Load(new PropertySet(EmailMessageSchema.TextBody));
// Output the body.
Console.WriteLine(itemAttachment.Item.TextBody);
}
}
For each email that had an item attachment I was able to see the body of the item with the HTML tags removed.
I hope this helps. If this solves your problem, please mark this post as answered.
Thanks,
--- Bob ---

SharePoint 2010 - Client Object Model - Add attachment to ListItem

I have a SharePoint List to which I'm adding new ListItems using the Client Object Model.
Adding ListItems is not a problem and works great.
Now I want to add attachments.
I'm using the SaveBinaryDirect in the following manner:
File.SaveBinaryDirect(clientCtx, url.AbsolutePath + "/Attachments/31/" + fileName, inputStream, true);
It works without any problem as long as the item that I'm trying to add the attachment to, already has an attachment that was added through the SharePoint site and not using the Client Object Model.
When I try to add an attachment to a item that doesnt have any attachments yet, I get the following errors (both happen but not with the same files - but those two messages appear consistently):
The remote server returned an error: (409) Conflict
The remote server returned an error: (404) Not Found
I figured that maybe I need to create the attachment folder first for this item.
When I try the following code:
clientCtx.Load(ticketList.RootFolder.Folders);
clientCtx.ExecuteQuery();
clientCtx.Load(ticketList.RootFolder.Folders[1]); // 1 -> Attachment folder
clientCtx.Load(ticketList.RootFolder.Folders[1].Folders);
clientCtx.ExecuteQuery();
Folder folder = ticketList.RootFolder.Folders[1].Folders.Add("33");
clientCtx.ExecuteQuery();
I receive an error message saying:
Cannot create folder "Lists/Ticket System/Attachment/33"
I have full administrator rights for the SharePoint site/list.
Any ideas what I could be doing wrong?
Thanks, Thorben
I struggled for a long time with this problem too, so I thought I'd post a complete code sample showing how to successfully create a list item and add an attachment.
I am using the Client Object API to create the list item, and the SOAP web service to add the attachment. This is because, as noted in other places on the web, the Client Object API can only be used to add attachments to an item where the item's upload directory already exists (eg. if the item already has an attachment). Else it fails with a 409 error or something. The SOAP web service copes with this OK though.
Note that another thing I had to overcome was that even though I added the SOAP reference using the following URL:
https://my.sharepoint.installation/personal/test/_vti_bin/lists.asmx
The URL that VS actually added to the app.config was:
https://my.sharepoint.installation/_vti_bin/lists.asmx
I had to manually change the app.config back to the correct URL, else I would get the error:
List does not exist.
The page you selected contains a list that does not exist. It may have been deleted by another user.
0x82000006
Here is the code:
void CreateWithAttachment()
{
const string listName = "MyListName";
// set up our credentials
var credentials = new NetworkCredential("username", "password", "domain");
// create a soap client
var soapClient = new ListsService.Lists();
soapClient.Credentials = credentials;
// create a client context
var clientContext = new Microsoft.SharePoint.Client.ClientContext("https://my.sharepoint.installation/personal/test");
clientContext.Credentials = credentials;
// create a list item
var list = clientContext.Web.Lists.GetByTitle(listName);
var itemCreateInfo = new ListItemCreationInformation();
var newItem = list.AddItem(itemCreateInfo);
// set its properties
newItem["Title"] = "Created from Client API";
newItem["Status"] = "New";
newItem["_Comments"] = "here are some comments!!";
// commit it
newItem.Update();
clientContext.ExecuteQuery();
// load back the created item so its ID field is available for use below
clientContext.Load(newItem);
clientContext.ExecuteQuery();
// use the soap client to add the attachment
const string path = #"c:\temp\test.txt";
soapClient.AddAttachment(listName, newItem["ID"].ToString(), Path.GetFileName(path),
System.IO.File.ReadAllBytes(path));
}
Hope this helps someone.
I have discussed this question with Microsoft. Looks like that only one way to create attachments remotely is List.asmx web service. I have tried to create this subfolder also and with no success.
With Sharepoint 2010 there was no way to upload a first attachment to a list item using the COM. The recommendation was to use the Lists web service inmstead.
With Sharepoint 2013 it works.
AttachmentCreationInformation newAtt = new AttachmentCreationInformation();
newAtt.FileName = "myAttachment.txt";
// create a file stream
string fileContent = "This file is was ubloaded by client object meodel ";
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] buffer = enc.GetBytes(fileContent);
newAtt.ContentStream = new MemoryStream(buffer);
// att new item or get existing one
ListItem itm = list.GetItemById(itemId);
ctx.Load(itm);
// do not execute query, otherwise a "version conflict" exception is rised, but the file is uploaded
// add file to attachment collection
newAtt.ContentStream = new MemoryStream(buffer);
itm.AttachmentFiles.Add(newAtt);
AttachmentCollection attachments = itm.AttachmentFiles;
ctx.Load(attachments);
ctx.ExecuteQuery();
// see all attachments for list item
// this snippet works if the list item has no attachments
This method is used in http://www.mailtosharepoint.net/
It reflects rather poorly on the Microsoft SharePoint team for not coming forward with an acknowledgement of the issue and a usable suggestion on how to resolve it. Here is how I dealt with it:
I am using the new SharePoint 2010 managed client that ships with the product. Hence, I already have a SharePoint ClientContext with credentials. The following function adds an attachment to a list item:
private void SharePoint2010AddAttachment(ClientContext ctx,
string listName, string itemId,
string fileName, byte[] fileContent)
{
var listsSvc = new sp2010.Lists();
listsSvc.Credentials = _sharePointCtx.Credentials;
listsSvc.Url = _sharePointCtx.Web.Context.Url + "_vti_bin/Lists.asmx";
listsSvc.AddAttachment(listName, itemId, fileName, fileContent);
}
The only prerequisite for the code above is to add to the project (I used Visual Studio 2008) a _web_reference_ I called sp2010 which is created from the URL of: http:///_vti_bin/Lists.asmx
Bon Chance...
HTML:
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
Event in code behind :
protected void UploadMultipleFiles(object sender, EventArgs e)
{
Common.UploadDocuments(Common.getContext(new Uri(Request.QueryString["SPHostUrl"]),
Request.LogonUserIdentity), FileUpload1.PostedFiles, new CustomerRequirement(), 5);
}
public static List<string> UploadDocuments<T>(ClientContext ctx,IList<HttpPostedFile> selectedFiles, T reqObj, int itemID)
{
List<Attachment> existingFiles = null;
List<string> processedFiles = null;
List<string> unProcessedFiles = null;
ListItem item = null;
FileStream sr = null;
AttachmentCollection attachments = null;
byte[] contents = null;
try
{
existingFiles = new List<Attachment>();
processedFiles = new List<string>();
unProcessedFiles = new List<string>();
//Get the existing item
item = ctx.Web.Lists.GetByTitle(typeof(T).Name).GetItemById(itemID);
//get the Existing attached attachments
attachments = item.AttachmentFiles;
ctx.Load(attachments);
ctx.ExecuteQuery();
//adding into the new List
foreach (Attachment att in attachments)
existingFiles.Add(att);
//For each Files which user has selected
foreach (HttpPostedFile postedFile in selectedFiles)
{
string fileName = Path.GetFileName(postedFile.FileName);
//If selected file not exist in existing item attachment
if (!existingFiles.Any(x => x.FileName == fileName))
{
//Added to Process List
processedFiles.Add(postedFile.FileName);
}
else
unProcessedFiles.Add(fileName);
}
//Foreach process item add it as an attachment
foreach (string path in processedFiles)
{
sr = new FileStream(path, FileMode.Open);
contents = new byte[sr.Length];
sr.Read(contents, 0, (int)sr.Length);
var attInfo = new AttachmentCreationInformation();
attInfo.FileName = Path.GetFileName(path);
attInfo.ContentStream = sr;
item.AttachmentFiles.Add(attInfo);
item.Update();
}
ctx.ExecuteQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
existingFiles = null;
processedFiles = null;
item = null;
sr = null;
attachments = null;
contents = null;
ctx = null;
}
return unProcessedFiles;
}
I've used and tried this one on my CSOM (SharePoint Client Object Model) application and it works for me
using (ClientContext context = new ClientContext("http://spsite2010"))
{
context.Credentials = new NetworkCredential("admin", "password");
Web oWeb = context.Web;
List list = context.Web.Lists.GetByTitle("Tasks");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><Where><Eq><FieldRef Name = \"Title\"/><Value Type=\"String\">New Task Created</Value></Eq></Where></View>";
ListItemCollection listItems = list.GetItems(query);
context.Load(listItems);
context.ExecuteQuery();
FileStream oFileStream = new FileStream(#"C:\\sample.txt", FileMode.Open);
string attachmentpath = "/Lists/Tasks/Attachments/" + listItems[listItems.Count - 1].Id + "/sample.txt";
Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, attachmentpath, oFileStream, true);
}
Note: Only works if item folder has been created already

Categories