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.

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:

This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>