Using Outlook Object Model

Written on November 27, 2007 – 8:52 pm | by Joseph Jude | Bookmark and Share

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.

Outlook Reference

Bring Outlook object model into project’s scope by ‘Using’ Directive


using Outlook = Microsoft.Office.Interop.Outlook;

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.

Outlook Warning

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:

Post a Comment

About Me

These pages are a reflection of me - my thoughts, passions and dreams. These pages are neither documentaries nor novels, rather just plain ramblings. I don’t promise to entertain you; at the same time hoping that I don’t bore you either. More

Want to subscribe?

 Subscribe in a reader
Find entries :