I use a very simple code to generate emails using outlook in my c# application. It works fine when Outlook is already opened.(Even though it asks for permission to open the email.But after I grant access a new Outlook message window opens with the generated email). But the real problem is if Outlook is not opened the application crashes at the line
Microsoft.Office.Interop.Outlook.Recipient oTORecipt = oMsg.Recipients.Add(email);
ERROR:An exception (first chance) of type 'System.Runtime.InteropServices.COMException' occurred in Birthday_Mailing.dll.
Additional information: discontinued operation (Exception from HRESULT: 0x80004004 (E_ABORT))
If a handler is available for this exception, the program may continue to run safely.
And my whole code can be seen as below
public void SendMail(string email, string name)
{
//// Create the Outlook application by using inline initialization.
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
////Create the new message by using the simplest approach.
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
Microsoft.Office.Interop.Outlook.Recipient oTORecipt = oMsg.Recipients.Add(email); //oRecips.Add(t);
oTORecipt.Type = (int)Microsoft.Office.Interop.Outlook.OlMailRecipientType.olTo;
oTORecipt.Resolve();
oMsg.Subject = "Herzlichen Glückwunsch";
oMsg.HTMLBody = "<html>" +
"<head>" +
"<title>Happy Birthday</title>" +
"</head>" +
"<body style='background-color:#E6E6E6;'>" +SelectImage+
"<div style='font-family: Georgia, Arial; font-size:14px; '>Liebe/r " + " " +
name + ",<br /><br />" +
"alles Gute zum <b>Geburtstag!</b> Wir wünschen einen schönen Tag und für das kommende Jahr Gesundheit, Glück und Erfolg." +
"<br /><br /><br /><br /><br />" +
"Mit den besten Grüßen,<br />" +
"XXYYZZ" +
"</div>" +
"</body>" +
"</html>";
oMsg.Save();
oMsg.Display();
oMsg = null;
oApp = null;
I'm not an expert in coding. Can someone help me to find where the actual problem is? Thanks in advance!
Microsoft.Office.Interop.Outlook.Inspector oInspector = oMsg.GetInspector;
I added this one line after declaring oMsg Object which solved the problem. But still before the message window opens Outlook asks for the users permission to display the email.
***Yet I wouldn't mark this as the Answer because it's not the best solution you can give for this question.
UPDATE: I found out that the above mentioned issue was due to some security system in our server. This is the correct answer. Thanks to @MikeMiller for showing the correct path
User contributions licensed under CC BY-SA 3.0