使用.NET C#我想从 *.msg文件加载Outlook HTML消息,添加收件人并将其保存到标准草稿文件夹。
我无法正确地使用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);
}
1条答案
按热度按时间5gfr0r5j1#
不要使用
mail.Close(Outlook.OlInspectorClose.olDiscard);
-您从未向检查员显示过,因此没有理由关闭它。此外,
Marshal.ReleaseComObject
不会做太多事情,因为您从未释放Recipients
集合和Recipients.Add
返回的Recipient
对象-它们都保留了对父消息的引用,并且您最终得到了两个从未释放的隐式变量。不要使用
DraftFolder.Items[1]
-调用Save
后将MailItem.EntryID
的值保存在变量中,然后使用Namespace.GetItemFromID
重新打开邮件。