我有以下代码
public void SendAttachmentsClick()
{
Microsoft.Office.Interop.Outlook.MailItem oMailItem = HostAddIn.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
oMailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
// //returns strings representing paths to documents I want to attach
List<string> paths = GetAttachmentsPaths();
if (paths.Count > 0)
{
foreach (string itemPath in paths)
{
oMailItem.Attachments.Add(itemPath);
}
if (oMailItem.Attachments.Count > 0)
{
oMailItem.Display(false);
}
}
}
呼叫 1:第一次呼叫SendAttachmentsClick()
打开新电子邮件并正确附加所有附件。
CALL 2:如果我在这封新电子邮件中单击取消,然后SendAttachmentsClick()
再次调用,我可以跟踪执行直到调用oMailItemAttachments.Add(itemPath)
上面(我在此代码中有断点)。但是,一旦在第二次调用中为第一个附件调用此行,整个 VSTO/outlook 就会崩溃。我添加了 try...catch 来尝试捕获异常,但它从未输入,所以我不知道错误是什么。
UPDATE1: 阅读 Eugene Astafiev 在https://www.add-in-express.com/creating-addins-blog/2011/08/10/how-to-add-attachment-to-e-mail- message/?thank=you&t=1467071796#comment-413803,我修改了上面的代码以释放 com 对象,现在看起来像这样,但问题仍然存在
public void SendAttachmentsClick()
{
Microsoft.Office.Interop.Outlook.MailItem oMailItem = HostAddIn.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
oMailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
Selection olSelection = HostAddIn.ActiveExplorer.Selection;
// //returns strings representing paths to documents I want to attach
List<string> paths = GetAttachmentsPaths();
if (paths.Count > 0)
{
try
{
Microsoft.Office.Interop.Outlook.Attachments mailAttachments = oMailItem.Attachments;
foreach (string itemPath in paths)
{
Microsoft.Office.Interop.Outlook.Attachment newAttachment = mailAttachments.Add(itemPath);
oMailItem.Save();
if (newAttachment != null) Marshal.ReleaseComObject(newAttachment);
}
if (oMailItem.Attachments.Count > 0)
{
oMailItem.Display(false);
}
if (mailAttachments != null)
Marshal.ReleaseComObject(mailAttachments);
if (oMailItem.Attachments != null)
Marshal.ReleaseComObject(oMailItem.Attachments);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (oMailItem != null)
{
Marshal.ReleaseComObject(oMailItem);
oMailItem = null;
}
Marshal.ReleaseComObject(olSelection);
}
}
}