【发布时间】:2016-10-29 23:53:33
【问题描述】:
我有以下代码
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);
}
}
}
CALL 1:第一次拨打SendAttachmentsClick()会打开新电子邮件并正确附加所有附件。
CALL 2:如果我在这封新电子邮件中单击“取消”,然后再次调用 SendAttachmentsClick(),我可以跟踪执行直到调用上面的 oMailItemAttachments.Add(itemPath)(我在这段代码中有断点)。但是,一旦在第二次调用中为第一个附件调用此行,整个 VSTO/outlook 就会崩溃。我添加了 try...catch 来尝试捕获异常,但它从未输入,所以我不知道错误是什么。
更新1: 在阅读了 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);
}
}
}
【问题讨论】:
-
我想知道您的 GetAttachmentsPaths() 是如何获取路径的。这些文件是否存在于您的本地计算机上,或者您正在从某个地方下载它们?如果您从某个地方下载它们,是否是您的取消逻辑正在删除下载?
-
我相信你是对的。你有什么建议?非常感谢
-
我会将下载的文件移动到另一个临时目录,从那里处理它们,然后删除临时目录。我在下面发布了部分解决方案。
-
我去看看,谢谢!
标签: c# vsto attachment mailitem