使用.net c#在Outlook 2019中保存html消息



使用。net c#,我想从*加载Outlook html消息。MSG文件,添加收件人并保存到标准草稿文件夹。

我不能正确地使用Outlook 2019(不是2016年或2013年),因为保存后,它将消息正文格式转换为纯文本。这只发生在2019年版本。在代码示例中,我首先创建电子邮件并将其保存为草稿。在COM应用程序对象被实例化之前,格式仍然是html。就在我手动打开Outlook.exe后,该消息已转为纯文本。我用PrintBodyFormat函数检查这一点。请注意,这只适用于Office 2019。

using Debug = System.Diagnostics.Debug;
using Outlook = Microsoft.Office.Interop.Outlook;
static void CreateMail()
{
Outlook.Application app = new Outlook.Application();
Outlook.MailItem mail = app.CreateItemFromTemplate(@"C:html_message.msg");
mail.Recipients.Add("johndoe@foobar.com");
Debug.WriteLine(mail.BodyFormat.ToString());
//OUTPUT WITH ALL OUTLOOK VERSION: "olFormatHTML"
mail.Save();
mail.Close(Outlook.OlInspectorClose.olDiscard);
System.Runtime.InteropServices.Marshal.ReleaseComObject(mail);
mail = null;
Outlook.NameSpace nms = app.GetNamespace("MAPI");
Outlook.MAPIFolder DraftFolder = nms.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts);
mail = DraftFolder.Items[1];
Debug.WriteLine(mail.BodyFormat.ToString());
//OUTPUT WITH ALL OUTLOOK VERSION: "olFormatHTML"
mail.Close(Outlook.OlInspectorClose.olDiscard);
System.Runtime.InteropServices.Marshal.ReleaseComObject(mail);
mail = null;
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(DraftFolder);
System.Runtime.InteropServices.Marshal.ReleaseComObject(nms);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
}
//Run this after manually opened Outlook.exe 
static void PrintBodyFormat()
{
Outlook.Application app = new Outlook.Application();
Outlook.NameSpace nms = app.GetNamespace("MAPI");
Outlook.MAPIFolder DraftFolder = nms.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts);
Outlook.MailItem mail = DraftFolder.Items[1];
Debug.WriteLine(mail.BodyFormat.ToString());
//OUTPUT WITH OUTLOOK 2016 OR EARLIER: "olFormatHTML"
//OUTPUT WITH OUTLOOK 2019: "olFormatPlain"
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(mail);
System.Runtime.InteropServices.Marshal.ReleaseComObject(DraftFolder);
System.Runtime.InteropServices.Marshal.ReleaseComObject(nms);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
}

不要使用mail.Close(Outlook.OlInspectorClose.olDiscard);-您从未显示过检查器,因此没有理由关闭它。

同样,Marshal.ReleaseComObject不会做太多事情,因为您从未释放Recipients集合和Recipients.Add返回的Recipient对象-它们都保持对父消息的引用,并且您最终得到两个您从未释放的隐式变量。

不使用DraftFolder.Items[1]-在调用Save后将MailItem.EntryID的值保存在一个变量中,然后使用它来使用Namespace.GetItemFromID重新打开消息

最新更新