C# Code to Send Outlook Mails Programmatically

This article demonstrates an example of sending outlook emails automatically by using C# code snippet. For this, you need to add a reference to the dynamic link library of Outlook called Microsoft.Office.Interop.Outlook.dll.

Follow the below-given steps for Outlook automation using C#.

1: In the Solution Explorer window, right-click the project then click Add Reference. In .NET tab, select Microsoft.Office.Interop.Outlook component and then click OK.

2: Now check that Microsoft.Office.Interop.Outlook has been added under the references.

3: Add the Outlook reference to your Class by placing this code in the list of namespaces.

using Outlook = Microsoft.Office.Interop.Outlook;

4: Below is the entire code of C# written in the method “SendOutlookMail”. Comments have been added at each code line to make you understand.

private void SendOutlookMail()
        {   
            try
            {   
                // creates outlook apllication object
                Outlook.Application oApp = new Outlook.Application();
                // creates new outlook mail item object
                Outlook.MailItem mailItem = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
                // sets the subject of mail
                mailItem.Subject = "Sample Mail Sending Example";
                // adds the attachment to the mail             
                mailItem.Attachments.Add("D:/Test/SampleAttachment.xlsx");
                // sets the To recepients of mail
                mailItem.To = "[email protected]";
                // sets the mail body
                mailItem.HTMLBody = "Hi, This is sample mail sending example.";
                // sets the mail importance
                mailItem.Importance = Outlook.OlImportance.olImportanceLow;                
                mailItem.Display(false);
                // sends the mail
                mailItem.Send();
            }
            catch (Exception ex)
            {
                
            }
        }

The above C# code will send the mail your outlook to mail ID mentioned in .To. While using this code you need to ensure that outlook is opened on your system. If outlook is not opened then this code will create and mail item but that mail will be stuck in the outbox and when you open outlook, then the mail will be sent. So it is suggested that you should use code to open outlook automatically using C# in the same program.

If you want to use tabular data in your mail body, you need to convert table to HTML code. You can refer to this post to get HTML code of data table then set mailItem.HTMLBody to htmlcode as shown below.

mailItem.HTMLBody = HtmlCode;

Leave a Reply