How to update HTMLBody of the MailItem

0

I`m trying to create outlook mails from templates, slightly edit them and then show to user so he can send that mail.

There is no problem in creation of the mail and displaying it. But when I`m trying to read (or edit) HTMLBody of the mail there is a error:

Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))

Here is my code:

using Outlook = Microsoft.Office.Interop.Outlook;
...

try
{
    var app = new Outlook.Application();

    Outlook.MailItem mailItem = app.CreateItemFromTemplate("C:\\Test\\template.oft");

    var body = mailItem.HTMLBody; //Here is the exception
    mailItem.HTMLBody = body.Replace("@firstname", "Test Testy");

    mailItem.To = message.EmailAddress;
    mailItem.Display(mailItem);
}
catch (Exception ex)
{
...
}

Added example project on github.

c#
email
outlook
office-interop
asked on Stack Overflow Oct 20, 2015 by JleruOHeP • edited Oct 20, 2015 by JleruOHeP

1 Answer

0
var app = new Outlook.Application();

Before creating a new instance of the Outlook Application class I'd suggest checking whether it is already run and get the running instance then:

if (Process.GetProcessesByName("OUTLOOK").Any())
   app = System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");

Outlook is a singleton. You can't run multiple instances at the same time.

Also I'd suggest saving the newvly created item before accessing the HTMLBody property value:

 Outlook.MailItem mailItem = app.CreateItemFromTemplate("C:\\Test\\template.oft");
mailIte.Save();
var body = mailItem.HTMLBody; //Here is the exception

Finally, the Display method doesn't take a MailItem instance. Instead, you can pass true to get the inspector shown as a modal window or just omit the parameter (false is used by default).

BTW Where and when do you run the code?

answered on Stack Overflow Oct 20, 2015 by Eugene Astafiev • edited Oct 20, 2015 by JleruOHeP

User contributions licensed under CC BY-SA 3.0