C# EWS Searching SentItems - c#

I'm new with C# and i'm making one *.exe that have to search emails with a specific subject in my Exchange.
For Inbox and Other Folders i use the code bellow (with no problems):
FindFoldersResults allEmailFolders_Inbox = service.FindFolders(WellKnownFolderName.Inbox, new FolderView(int.MaxValue) { Traversal = FolderTraversal.Shallow });
FindFoldersResults allEmailFolders = service.FindFolders(WellKnownFolderName.Inbox, new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep });
Now i'm trying to search inside Sent Item Folder, but don't return me results. If i make a new folder inside SentItems the email apeears, but inside Sent items no. I try the code bellow:
FindFoldersResults allEmailFolders_Sent = service.FindFolders(WellKnownFolderName.SentItems, new FolderView(int.MaxValue){Traversal=FolderTraversal.Deep});
FindFoldersResults allEmailFolders_Sent = service.FindFolders(WellKnownFolderName.SentItems, new FolderView(int.MaxValue){Traversal=FolderTraversal.Shallw});
Can someone help me?

The lines of code you've shown are searching for folders inside the inbox or inside the sent items folder, not email. You might want to take a look at the Search topics in MSDN: https://msdn.microsoft.com/EN-US/library/office/dn579421(v=exchg.150).aspx. There are links to a number of search samples there as well. This one seems relevant to your scenario: https://code.msdn.microsoft.com/exchange/Exchange-2013-Search-for-2ea5597e/sourcecode?fileId=84155&pathId=889776652

Related

Moving mailitems from MAPIFolder to normal directory on Disc in zipped form

I am trying to access individual mailitems from a .pst file in C#. I want to filter mails based on some input parameters. These filtered mails i want to zip and store in a particular location. i am able to filter mails based on the criteria but instead of moving the mails to particular destination folder i am able to move them only to MAPIFolder. Can anyone help?
Outlook.MAPIFolder destFolder = rootFolder.Folders["Test"];
((MailItem)item).Move(destFolder);
the above code i have implemented.
But i need something like
Folder destFolder = Path(#"C:\FilteredMails\");
((MailItem)item).Move(destFolder);
Kindly help.
Call MailItem.SaveAs(..., olMsg) to save a message as an MSG file, then delete the message using MailItem.Delete.

Using multiple DirectoryInfo calls with GoDaddy causes an error?

I'm wondering if anyone has come across this issue or knows of a better way to do this with GoDaddy as the web host?
First off I'll say this code works just fine when I run it locally. It's only when I put it out on a GoDaddy site that is causes an error. The idea behind the code is that I want to look at a "Galleries" folder and inside of that main folder I have folders like "Completed" and "Current". This is where the end user will put different folders underneath those. I then get all of those subfolders into a List which I use to create a as hyperlinks. Those hyperlinks will get all the files in that folder and display them in an image gallery.
Again, it works just fine locally but when I put it on GoDaddy I get an error like "Could not find a part of the path 'G:\PleskVhosts\websitename\httpdocs\aaw\Galleries\Current".
Doing some troubleshooting, if I just do the first directory it works fine on GoDaddy. It's not until I add a second or more that I get the above error. I'm stumped as to why I would get this since they are all in their own variables and Lists.
Here is a sample of the code. If I only use the first DirectoryInfo then all is good. It's not until I add the second one that the issue arises.
DirectoryInfo dirComplete = new DirectoryInfo(HostingEnvironment.MapPath("/Galleries/Completed/"));
DirectoryInfo[] completedFolderList = dirComplete.GetDirectories();
var completedFolders = new List<Gallery>();
foreach (var folder in completedFolderList)
{
var gallery = new Gallery();
gallery.GalleryName = folder.Name;
completedFolders.Add(gallery);
}
DirectoryInfo dirCurrent = new DirectoryInfo(HostingEnvironment.MapPath("/Galleries/Current/"));
DirectoryInfo[] currentFolderList = dirCurrent.GetDirectories();
var currentFolders = new List<Gallery>();
foreach (var folder in currentFolderList)
{
var gallery = new Gallery();
gallery.GalleryName = folder.Name;
currentFolders.Add(gallery);
}
var vm = new GalleriesViewModel();
vm.CompletedGalleries = completedFolders;
vm.CurrentGalleries = currentFolders;

How to check email for file using c#?

I receive an email with an excel file every week. I know there are probably better ways to accomplish my goal, but would it be possible to have a script task in SSIS that can open email, look for a specific file name as an attachment and then copy that file to another location?
Here is the scenario. This excel file is important for my team to have in a SQL database, and the provider of the excel source is only willing to email this excel file to us once per week. I then check my email, copy the file to a location where an SSIS dataflow task can then pick it up and insert it into a SQL table. I would like to automate this. So if my original approach is not doable, how else could this be automated? Aside from using a shared network location. Assume the excel file can ONLY come from the email. Using outlook/office 365, SSIS, SSMS, I have DBO access, and can use c#.
I'll admit that I'm ignorant on the email. If there is a procedure that the email client can actually execute to accomplish this, then I'd be all ears!
EDIT: I also have access to a network drive as I realize saving to my local machine may be impossible.
Simple Answer Yes it is Possible.
I had written a console program to process email on Office365 that I was also interfacing with SQL, so it definitely can be done. It isn't necessarily the easiest thing in the world but it is not too hard either.
You can use the Exchange Web Services (EWS) Managed API
Article on stating it is possible and the API documentation
https://msdn.microsoft.com/en-us/library/office/dd877012(v=exchg.150).aspx
Github location where you can find the API (note this link is directly form Microsoft's Site)
https://github.com/officedev/ews-managed-api
Link on how to reference the assembly which contains the second link above:
https://msdn.microsoft.com/en-us/library/office/dn528373(v=exchg.150).aspx
Create and Connect to Service
string emailAddress = 'YourEmail#Domain.com';
ExchangeService exService = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
exService.Credentials = new WebCredentials(emailAddress,"password");
you can autodiscover or if you know the URL just set it so 1 of these lines
exService.AutodiscoverUrl(_emailAddress, delegate { return true; });
exService.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
Find your Inbox & a Folder to Move the File To After Being Processed:
FolderView folderView = new FolderView(1);
folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly);
folderView.PropertySet.Add(FolderSchema.DisplayName);
folderView.Traversal = FolderTraversal.Deep;
SearchFilter searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "ProcessedFolderName");
Folder Inbox = Folder.Bind(exService, WellKnownFolderName.Inbox);
FindFoldersResults folderResults = Inbox.FindFolders(searchFilter, folderView);
FolderId processedFolderId = folderResults.Folders[0].Id;
Find Messages That meet your criteria:
List<SearchFilter> searchFilterCollection = new List<SearchFilter();
searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject,"Words in Subject"));
searchFilterCollection.Add(new SearchFilter.IsEqualTo(ItemSchema.HasAttachments,true));
searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.From,new EmailAddress("From#SendersDomain.com")));
SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And,searchFilterCollection);
ItemView view = new ItemView(50, 0, OffsetBasePoint.Beginning);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.DateTimeReceived, ItemSchema.Attachments);
view.Traversal = ItemTraversal.Shallow;
FindItemsResults<Item> findResults = exService.FindItems(WellKnownFolderName.Inbox,searchFilter,view);
Process the results and save the attachments when done move the message to another folder so you don't keep importing the same one.
foreach (Item i in findResults.Items)
{
foreach(FileAttachment attachment in i.Attachments)
{
attachment.Load(#"\\FilePathDirectory\" + attachment.FileName);
}
i.Move(processedFolderId);
}
you can expand the solution by testing if you get no results sending yourself an error message or throwing an error for SSIS to pickup and fail the job. It is likely that you will overwrite the file multiple times if you have multiple messages to process so you may consider adding something unique in the file name instead of just using the same one but that will present other challenges in SSIS as well.
anyway, its a start hope it helps.

mailkit Add imap folder not visible

I'm trying to add folder to inbox as follows:
var _client = new ImapClient();
_client.Connect(hostName, portNumber, useSsl);
_client.Authenticate(username, password);
_client.Inbox.Open(FolderAccess.ReadWrite);
_client.Inbox.Create("Name", true);
Everything goes fine, the Create function returns created folder, the _client.Inbox.GetSubfolders() returns list that contains new created folder as well, however I can't see this folder in e-mail client application (such as Thunderbird).
What am I doing wrong?
Thunderbird may only be showing you subscribed folders. If that is the case, then you will also want to do newFolder.Subscribe ();
I should also point out that there's no reason to Open() the inbox before creating a child folder.
You only need to Open() a folder in order to read messages from it.

Open Specific MailItem in Outlook from C#

I want to open a specific email in Outlook from my C# winforms application.
At the moment I have got the following code:
//...Get Folder & Entry ID for last Email in Sent Box
Outlook.Application myApp = new Outlook.ApplicationClass();
Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
Outlook.MAPIFolder mySentBox = mapiNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
Outlook.MailItem myMail = ((Outlook.MailItem)mySentBox.Items[1]);
string guid = myMail.EntryID;
string folderEntryID = mySentBox.EntryID;
string folderStoreID = mySentBox.StoreID;
string mailAddressee = myMail.To;
MessageBox.Show(mailAddressee);
//...Attempt to Open that Email at a later date
Outlook.MAPIFolder getFolder = (Outlook.MAPIFolder)mapiNameSpace.GetFolderFromID(folderEntryID, folderStoreID);
Outlook.MailItem getItem = (Outlook.MailItem)getFolder.Items.Find("[EntryID] = " + guid);
getItem.Display();
The first an second parts of the code will be run at different times, although they are in the same Method for testing at the moment.
The first part obtains the relevant IDs for the mst recently sent email from Outlook. This part seems to work fine as evidence my the Messagebox I've built in.
The second part however is not working and I'm struggling to find the right code to access and open that specific mailItem having obtained its ID and folder location in the first part.
Anyone able to complete this little project for me please.
Done it at last by replacing the following lines of code . . .
Outlook.MAPIFolder getFolder = (Outlook.MAPIFolder)mapiNameSpace.GetFolderFromID(folderEntryID, folderStoreID);
Outlook.MailItem getItem = (Outlook.MailItem)getFolder.Items.Find("[EntryID] = " + guid);
with this . . .
Outlook.MailItem getItem = (Outlook.MailItem)mapiNameSpace.GetItemFromID(guid, folderStoreID);
You can not use EntryId with the _Items.Find method. The MSDN reference is here.
There is also a remark which could be interesting for your project:
"The Entry ID changes when an item is moved into another store, for
example, from your Inbox to a Microsoft Exchange Server public folder,
or from one Personal Folders (.pst) file to another .pst file.
Solutions should not depend on the EntryID property to be unique
unless items will not be moved."
MailItem.EntryID Property (Outlook).

Categories

Resources