Outlook object model provides a more extensible object collections to send and read items. This blog speaks about how to read a email from outlook default profile and process the attachment. The Outlook Item object has a method called Find which allows to filter the mail based on subject, To, cc etc. The below code will get all the mail item with the specified subject. If the item has an attachment it will save it to the path specified.
To begin with Add a Outlook interop assembly to the reference in the project
Once added please copy paste the below code to run the sample
Code Snippet
- try
- {
- Microsoft.Office.Interop.Outlook.Application MyApp = new Microsoft.Office.Interop.Outlook.Application();
- Microsoft.Office.Interop.Outlook.NameSpace MailNS = MyApp.GetNamespace("mapi");
- MailNS.Logon(MyApp.DefaultProfileName, Missing.Value, false, true);
- Microsoft.Office.Interop.Outlook.MAPIFolder MyInbox = null;
- MyInbox = MailNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
- Microsoft.Office.Interop.Outlook._MailItem InboxMailItem = null;
- Microsoft.Office.Interop.Outlook.Items oItems = MyInbox.Items;
- ////string Query = "[Subject] = '" + Properties.Settings.Default.EmailSubject + "'";
- string Query = "[Subject] = 'my sample search text'";
- InboxMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oItems.Find(Query);
- while (InboxMailItem != null)
- {
- ListViewItem myItem = lvwMails.Items.Add(InboxMailItem.SenderName);
- myItem.SubItems.Add(InboxMailItem.Subject);
- string AttachmentNames = string.Empty;
- foreach (Microsoft.Office.Interop.Outlook.Attachment item in InboxMailItem.Attachments)
- {
- AttachmentNames += item.DisplayName;
- ////item.SaveAsFile(this.GetAttachmentPath(item.FileName, Properties.Settings.Default.ReceiveAttachmentPath));
- item.SaveAsFile(this.GetAttachmentPath(item.FileName, "c:\\test\\attachments\\"));
- }
- myItem.SubItems.Add(AttachmentNames);
- InboxMailItem.Delete();
- InboxMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oItems.FindNext();
- }
- ////MailMsg.Send();
- MailNS.Logoff();
- MailNS = null;
- MyInbox = null;
- InboxMailItem = null;
- ((Microsoft.Office.Interop.Outlook._Application)MyApp).Quit();
- ////MyApp.Quit();
- MyApp = null;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
the getattachmentpath method implementation is below. This method will check for any existing attachment with the same name and adds running number if exists
Code Snippet
- private string GetAttachmentPath(string AttachfileName, string AttachPath)
- {
- string filename = Path.GetFileNameWithoutExtension(AttachfileName);
- string ext = Path.GetExtension(AttachfileName);
- int app = 0;
- if (File.Exists(AttachPath + filename + ext))
- {
- while (File.Exists(AttachPath + filename + app + ext))
- {
- app++;
- }
- filename = filename + app;
- }
- return AttachPath + filename + ext;
- }
Hello, Reading your weblog is a real pleasure, thanks !