13 Haz

C# Send an Email Using Outlook Program

To send an email using outlook program, we need to add a reference to the dynamic link library for Outlook which is called Microsoft.Office.Interop.Outlook.dll. To do this, firstly go to your solution explorer and click on add a reference. Then, add Microsoft.Office.Interop.Outlook.dll.

Sample code and usage are below.

Usage:

            //using MsOutlook = Microsoft.Office.Interop.Outlook;
            //You must add using statement.

            string[] attachFiles = new string[] { 
                @"C:\test.txt"
            };
            SendMailWithOutlook("Subject1", "This is an example.", "test@csharpexample.com", attachFiles, MailSendType.SendDirect);

Code:

        public enum MailSendType
        {
            SendDirect = 0,
            ShowModal = 1,
            ShowModeless = 2,
        }

        public bool SendMailWithOutlook(string subject, string htmlBody, string recipients, string[] filePaths, MailSendType sendType)
        {
            try
            {
                // create the outlook application.
                MsOutlook.Application outlookApp = new MsOutlook.Application();
                if (outlookApp == null)
                    return false;

                // create a new mail item.
                MsOutlook.MailItem mail = (MsOutlook.MailItem)outlookApp.CreateItem(MsOutlook.OlItemType.olMailItem);

                // set html body. 
                // add the body of the email
                mail.HTMLBody = htmlBody;

                //Add attachments.
                if (filePaths != null)
                {
                    foreach (string file in filePaths)
                    {
                        //attach the file
                        MsOutlook.Attachment oAttach = mail.Attachments.Add(file);
                    }
                }

                mail.Subject = subject;
                mail.To = recipients;
                
                if (sendType == MailSendType.SendDirect)
                    mail.Send();
                else if (sendType == MailSendType.ShowModal)
                    mail.Display(true);
                else if (sendType == MailSendType.ShowModeless)
                    mail.Display(false);

                mail = null;
                outlookApp = null;
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }