Monday 10 January 2011

Send/Read an email from OUTLOOK using C#

Using this code you can send an Email from OUTLOOK and even you can Read an Email.
Here I am assuming that you have outlook installed on the machine where you are running this code.
Send an Eamil:
using Outlook = Microsoft.Office.Interop.Outlook;
public void sendEmail()
{
try
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody =”Hello,Jawed”;
String sDisplayName = "MyAttachment";
int iPosition = (int)oMsg.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
Outlook.Attachment oAttach = oMsg.Attachments.Add(“C:\\testFile.jpg”, iAttachType, iPosition, sDisplayName);
oMsg.Subject = “This is my outLook email test”;
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("jawed.ace@gmail.com");
oRecip.Resolve();
oMsg.Send();
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}
Catch(Exception ex)
{
//
}
}

Read an Email From OUTLOOK:
using Outlook = Microsoft.Office.Interop.Outlook;
public void readEmail()
{
try
{
Outlook.Application myApp = new Outlook.ApplicationClass();
Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
//Read all the email one by one
for (int i = myInbox.Items.Count; i >=( myInbox.Items.Count-1);i--)
{
String strSubject = ((Outlook.MailItem)myInbox.Items[i]).Subject;
// Sender Email
string senderEmailid = ((Outlook.MailItem)myInbox.Items[i]).SenderEmailAddress;
string CreationTime=(( Outlook.MailItem)myInbox.Items[i]).CreationTime.ToString();

string strEmailBody=(( Outlook.MailItem)myInbox.Items[i]).Body;

string strEmailSenderName=(( Outlook.MailItem)myInbox.Items[i]).SenderName;

Console.WriteLine(“Subject: ”+strSubject);
Console.WriteLine(“sender Emailid: ”+ senderEmailid);
Console.WriteLine(“Creation Time: ”+ CreationTime);
Console.WriteLine(“Email Body: ”+ strEmailBody);

}
}

Hope this would be helpful for you!!
Feel free to post your comments.
~jawed
Catch(Exception ex)
{

]
}

5 comments:

Mehboob Ali said...

Yar i did n't find Interop in Microsoft.Office Namespace,also i want to know can i use your code in my web application or not.i had build a website to send emails & show sent emails but how can i read mails that comes in his/her outlook inbox.

plz help me in this regard.

Thanks
Mehboob Ali PK

Anonymous said...

Thanks! It helps alot.

Anonymous said...

Just change Outlook.Application myApp = new Outlook.ApplicationClass(); to Outlook.Application myApp = new Outlook.Application(); and it will work

Anonymous said...

even with Outlook.Application myApp = new Outlook.Application(); it dosent work ,what could be the problem

Anonymous said...

It works really fine!!!