C# code to send an email using Microsoft Outlook Object Library

using System;

using System.Reflection;

using Outlook = Microsoft.Office.Interop.Outlook;

 

namespace SendMail

{

    public class Test

    {

        public static int Main(string[] args)

        {

            try

            {

                // Create the Outlook application.

                Outlook.Application oApp = new Outlook.Application();

 

                // Get the NameSpace and Logon information.

                Outlook.NameSpace oNS = oApp.GetNamespace("mapi");

 

                // Log on by using a dialog box to choose the profile.

                oNS.Logon(Missing.Value, Missing.Value, true, true);

 

                // Create a new mail item.

                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

 

                // Set the subject.

                oMsg.Subject = "Sent Using Microsoft Outlook Object Library in C#";

 

                // Set HTMLBody.

                String sHtml;

                sHtml = "<HTML>\n" +

                   "<HEAD>\n" +

                   "<TITLE>Sample GIF</TITLE>\n" +

                   "</HEAD>\n" +

                   "<BODY><P>\n" +

                   "<h1><Font Color=Blue>Hello Universe</Font></h1></P>\n" +

                   "</BODY>\n" +

                   "</HTML>";

                oMsg.HTMLBody = sHtml;

 

                // Add a recipient.

                Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;

                // TODO: Change the recipient in the next line if necessary.

                Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("foo@foo.com");

                oRecip.Resolve();

 

                // Send.

                oMsg.Send();

 

                // Log off.

                oNS.Logoff();

 

                // Clean up.

                oRecip = null;

                oRecips = null;

                oMsg = null;

                oNS = null;

                oApp = null;

            }

 

            // Simple error handling.

            catch (Exception e)

            {

                Console.WriteLine("{0} Exception caught.", e);

            }

 

            // Default return value.

            return 0;

        }

    }

}

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s