Software Architecture – To send email with attachments via C# 4.0 + Office Interop Outlook

Objective:
Objective of this code is to read files from a folder, compose an email via MS Outlook and send email with all the files attached to it.

Environment:
MS Visual Studio 2010 + C# 4.0 + Office Interop Outlook
Solutiuon:
The types and members of the Microsoft.Office.Interop.Outlook namespace provide support for interoperability between the COM object model of Microsoft Outlook and managed applications that automate Outlook.

 oApp = new Microsoft.Office.Interop.Outlook.Application();
            oNameSpace = oApp.GetNamespace("MAPI");
            oNameSpace.Logon(null, null, true, true);
            oOutboxFolder = oNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox);
            Microsoft.Office.Interop.Outlook._MailItem oMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
            oMailItem.To = "shahzad@comsoftuae.com";
            oMailItem.Subject = "Daily Backup Dated -" + DateTime.Now;
            oMailItem.Body = "Daily Backup Dated -" + DateTime.Now;
            oMailItem.SaveSentMessageFolder = oOutboxFolder;
            //uncomment this to also save this in your draft      
            oMailItem.Save();
            /// Send all files in Backup Folder
            DirectoryInfo dir = new DirectoryInfo("F:\\e-pros\\testbest\\SSISFirst\\SSISFirst\\bin\\");
            foreach (var item in dir.GetFiles())
            {
                oMailItem.Attachments.Add(item.FullName, Type.Missing, Type.Missing, Type.Missing);
            }
            // Clear all files from backup folder
            foreach (var item in dir.GetFiles())
            {
                item.Delete();
            }
            
            //adds it to the outbox      
            oMailItem.Send();

Related Post: https://softarchitect.wordpress.com/2010/09/18/software-architecture-sync-data-between-offlinedisconnected-databases-ssis-bids/

Advertisements

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

%d bloggers like this: