Introduction: Here is the code to read mail from outlook.
The outlook is software developed by Microsoft to configure your mail box on
your computer. And by using this code we can use outlook mails to process our
requirement. The attachment with mails is also processed in this article.
NameSpace :
First of all you need to
add a reference for ‘Microsoft.Office.Interop.Outlook’
And the use this namespace on your page.
using OutlookApplication = Microsoft.Office.Interop.Outlook;
Code :
Here is the complete code to read mails from outlook :
{
OutlookApplication._Application
outlook = new OutlookApplication.ApplicationClass();
OutlookApplication._NameSpace Oname =
outlook.GetNamespace("MAPI");
Oname.Logon("your default outlook profile
name", Missing.Value, false, false);
OutlookApplication._SyncObject
_syncObject = null;
_syncObject = Oname.SyncObjects[1];
_syncObject.Start();
//System.Threading.Thread.Sleep(30000);
_syncObject.Stop();
_syncObject = null;
Microsoft.Office.Interop.Outlook.MAPIFolder
myInbox = Oname.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
OutlookApplication.Items attachItems
= myInbox.Items;
string filter = "@SQL="
+ "urn:schemas:httpmail:subject LIKE '%HELLO%'
AND "
+ "urn:schemas:httpmail:datereceived >= '"
+ (DateTime.Now.ToUniversalTime()).ToString("MM/dd/yyyy") + "'
AND "
+ "urn:schemas:httpmail:hasattachment = True";
attachItems = attachItems.Restrict(filter);
if (attachItems.Count > 0)
{
foreach (OutlookApplication.MailItem
mail in attachItems)
{
//mail.SenderEmailAddress;
foreach (OutlookApplication.Attachment attach in
mail.Attachments)
{
//check for Path.GetExtension(attach.FileName)
== ".zip"
if (attach.Size > 0 & attach.Type
== OutlookApplication.OlAttachmentType.olByValue)
{
//SAVE FILE
mail.UnRead = false;
}
}
}
}
attachItems = null;
myInbox
= null;
Oname.Session.Logoff();
Oname.Logoff();
Oname =
null;
outlook.Quit();
outlook
= null;
GC.Collect();
GC.WaitForPendingFinalizers();
}