Sending Email through Outlook 2010 via C#

SteveAnselment picture SteveAnselment · Nov 11, 2013 · Viewed 88.3k times · Source

I am trying to send an email from inside my C# console App. I have added the references and using statements but it seems I have not added everything I need. This is the first time I have ever attempted to do this so I figure there is something I have forgotten.

I got this code snippet from the MSDN site http://msdn.microsoft.com/en-us/library/vstudio/ms269113(v=vs.100).aspx

ScreenShot of code from VS2010 showing the build errors

Here is the code that I am getting issues with in VS 2010

using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Runtime.InteropServices;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

namespace FileOrganizer
{
    class Program
    {
        private void CreateMailItem()
        {
            //Outlook.MailItem mailItem = (Outlook.MailItem)
            // this.Application.CreateItem(Outlook.OlItemType.olMailItem);
            Outlook.Application app = new Outlook.Application();
            Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem);
            mailItem.Subject = "This is the subject";
            mailItem.To = "[email protected]";
            mailItem.Body = "This is the message.";
            mailItem.Attachments.Add(logPath);//logPath is a string holding path to the log.txt file
            mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
            mailItem.Display(false);
        }
    }
}

Answer

Marvin Smit picture Marvin Smit · Nov 11, 2013

replace the line

Outlook.MailItem mailItem = (Outlook.MailItem)
this.Application.CreateItem(Outlook.OlItemType.olMailItem);

with

Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

Hope this helps,