0

I am trying to send a confirmation email when a user submits a form. I had privlage problems with smtp so I am trying to do it through Outlook. The code works fine enter link description here when Outlook isn't open but just hangs when it is. Any ideas how to fix this or ways around it?

try
{

// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();

// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set HTMLBody. 
//add the body of the email
oMsg.HTMLBody = "Hello, Jawed your message body will go here!!";

//Subject line
oMsg.Subject = "Your Subject will go here.";

 // Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("email@address.com");
oRecip.Resolve();

// Send.
((Outlook._MailItem)oMsg).Send();


// Clean up.
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oMsg);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oRecip);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oRecips);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oApp);
}//end of try block

catch (Exception ex)
{
}//end of catch
joetinger
  • 2,589
  • 6
  • 29
  • 43
  • Have you tried checking to see if an existing instance of Outlook is open and using it if there is one, then if there isn't one creating a new instance? – Ben Black Apr 03 '14 at 15:54
  • There is an instance open on my comp. I'm not sure how I would use that instance – joetinger Apr 03 '14 at 15:56

1 Answers1

1

Try checking to see if there is an instance of Outlook already open, if there is one use it to send the mail. If not then create the new instance.

(Untested) this should get you started:

Outlook.Application oApp;
try { 
    oApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application"); 
}
catch () {
    oApp = new Outlook.Application();
}

// use oApp to send the stuff, it will either be the existing instance or a new instance
Ben Black
  • 3,751
  • 2
  • 25
  • 43
  • Thanks that worked. I had to run Outlook as administrator to get it going http://stackoverflow.com/questions/15228845/how-to-connect-to-a-running-instance-of-outlook-from-c-sharp Thanks for the help! – joetinger Apr 03 '14 at 16:19