I am writing a C# application and part of it is to use Outlook to send out an email. It is working fine when Outlook is running, however, I get an error window "Object reference not set to an instance of an object" when Outlook is not running. The error happens at line email.Send(). Here is the code
Outlook.Application app = null;
try
{
if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Count() > 0)
{
app = System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
}
else
{
app = new Outlook.Application();
Outlook.NameSpace ns = app.GetNamespace("MAPI");
ns.Logon(Type.Missing, Type.Missing, false, false);
}
Outlook.MailItem eMail = app.CreateItem(Outlook.OlItemType.olMailItem);
eMail.Subject = "Test";
eMail.To = "
a...@xxx.com";
eMail.Body = string.Empty;
eMail.Send();
}
catch (Exception ex)
{
throw ex;
}
Any suggestion is appreciated.