Monday, July 6, 2009

How to Access Outlook Emails with ASP.NET ,C#

Hi,
on my first post, i have covered how to add Refrences
on you'r .net application
now we require same thing to Send / Receive Mail via outlook using ASP.NET.
To acquire these, all you need is Interop.Outlook.dll.

Stpes :
1. Create one Project as "OutlookSendReceive" .
2. include "Bin" folder on same , right click on it , select Add refrence
then click tab "COM " and select " Microsoft Outlook 11.0 " click ok

3. it will add assemblies on you'r web.config page
like

<assemblies>
<add assembly="Microsoft.Office.Interop.Outlook, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e29c34"/>
</assemblies>

4. Define
"using Microsoft.Office.Interop.Outlook;
using System.Text;"

5. copy that code on Page_load() event


Microsoft.Office.Interop.Outlook.Application nOutlook;
Microsoft.Office.Interop.Outlook.NameSpace oNs;
Microsoft.Office.Interop.Outlook.MAPIFolder oFldr;

try
{
nOutlook = new Microsoft.Office.Interop.Outlook.Application();
oNs = nOutlook.GetNamespace("MAPI");

//getting mail folder from inbox
oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Response.Write("Total Mail in Inbox :" + oFldr.Items.Count + "
");
Response.Write("Total Unread items = " + oFldr.UnReadItemCount);
foreach (Microsoft.Office.Interop.Outlook.MailItem oMessage in oFldr.Items)
{
StringBuilder str = new StringBuilder();
str.Append("<table><tr><td><b>Sender :</b></td><td>");
str.Append(oMessage.SenderEmailAddress.ToString() + "</td></tr>");

//Define Additional Information of Message
str.Append("<tr><td><b>Date :</b></td><td>" + oMessage.SentOn.ToShortDateString() + "</td></tr>");
if (oMessage.Subject != null)
{
str.Append("<tr><td><b>Subject :</b></td><td>" + oMessage.Subject.ToString() + "</td></tr>");
}

str.Append("</table><br>");
Response.Write(str.ToString());
}

}
catch (System.Exception ex)
{
Response.Write("Execption generated:" + ex.Message);
}
finally
{
GC.Collect();
oFldr = null;
oNs = null;
nOutlook = null;
}




like this way you can access Outlooks mail ,
thank you,
will come up more on how to access gmail /yahoo mail directly

1 comment:

  1. Very nice post. I just stumbled upon your weblog and wanted to say that I have
    truly enjoyed surfing around your blog posts.

    After all I'll be subscribing to your rss feed and I
    hope you write again soon!

    My web site :: basement contractors Toronto

    ReplyDelete