Archive for November, 2007
Using Outlook Object Model
Quite often it becomes necessary to send emails from applications that one develop. .NET framework provides multiple options for sending mails. For client side applications, using Outlook Object Model is the easiest one. This article describes how to use Outlook Object Model in C# for notifications.
Within Visual Studio IDE, add COM reference to Outlook Object Library as shown in the below image.

Bring Outlook object model into project’s scope by ‘Using’ Directive
Rest of the code is simple and self-explanatory.
Outlook.Application OutlookApp = new Outlook.Application(); Outlook.MailItem OppyMsg = (Outlook.MailItem)OutlookApp.CreateItem(Outlook.OlItemType.olMailItem); OppyMsg.To = MsgTo; //Change this to TO email id OppyMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatPlain; OppyMsg.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceNormal; OppyMsg.Subject = MsgSubject; //Change this to the subject //send it finally (OppyMsg as Outlook._MailItem).Send(); //casting is needed; or else ambiguity error occurs
Depending on Outlook security settings, there might be a warning dialog box.

If the user presses, “No”, it will raise a COM Exception. It has to be handled.
//send it finally
try
{
(OppyMsg as Outlook._MailItem).Send();
}
catch(System.Runtime.InteropServices.COMException MsgException)
{
//user pressed abort; dont worry get on
if (MsgException.ErrorCode == -2147467260)
{
return;
} }
That is it!
Tools Used: Visual Studio 2005, Outlook 2003
References: