VSTO C# MailItem.Attachments.Add() Crashes

本文关键字:Crashes Add Attachments MailItem VSTO | 更新日期: 2023-09-27 17:52:34

我有以下代码

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:如果我在这个新的电子邮件消息中单击Cancel,然后再次调用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);
        }
    }
}

VSTO C# MailItem.Attachments.Add() Crashes

按照建议,我会这样做。你不必像上面那样保存你的邮件。请注意,我没有为您提供getattachmentspath方法的逻辑,因为我不知道您是如何做到这一点的,但在我看来,您正在从某个地方下载文件,并且您确认了这一点。但是,我确实提供了非常好的说明如何编写此方法并返回下载文件的路径。希望对你有帮助。

public async void SendAttachmentByMailClick()
{
    // delete temp directory if it exists, then create brand new one each time
    var tempFolder = Path.Combine(Path.GetTempPath(), "MyTempFolder");
    if (Directory.Exists(tempFolder)) 
    { 
        Directory.Delete(tempFolder, true); 
    }
    Directory.CreateDirectory(tempFolder);
    // get your list asynchronously
    List<string> paths = null; 
    try  
    {
        // I am doing this asynchronously but awaiting until I get files.  I
        // would use a TaskCompletionSource (google for it) and once you
        // receive each file, store it's path in a List<string> object.
        // Check that the List<string> Count is equal to passed in
        // selection.Count and when it is, pass the list to TrySetResult()
        // of TaskCompletionSource.  Wrap that in try...catch and in catch
        // block pass the exception to TrySetException method of 
        // TaskCompletionSource.  This method should await and return
        // Task object of TaskCompletionSource which will then contain the
        // list of paths to your downloaded files.  Then you move one with 
        // logic below to copy them to temp location and attach them from 
        // there.
        paths = await GetAttachmentsPaths(MyAddIn.ActiveExplorer.Selection);
    }
    catch (Exception e) 
    {
        // handle exceptions 
        return;
    }
    // create new message
    Microsoft.Office.Interop.Outlook.MailItem oMailItem = MyAddIn.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); 
    if (paths != null && paths.Count > 0)
    {
        var attachmentFileName = String.Empty; 
        try
        {
            // if list has downloaded files, copy them to tempFolder
            List<string> copiedPaths = GetCopiedPaths(tempFolder, paths);
            if (copiedPaths.Count > 0)
            {
                // then attach each from that location
                foreach (var itemPath in copiedPaths)
                {
                    FileInfo fInfo = new FileInfo(itemPath);
                    if (fInfo.Exists)
                    {
                        attachmentFileName = fInfo.Name; 
                        oMailItem.Attachments.Add(itemPath, OlAttachmentType.olByValue, 1, fInfo.Name);
                    }
                    // delete file once attached to clean up
                    fInfo.Delete();
                }
            }
            if (oMailItem.Attachments.Count > 0)
            {
                oMailItem.Display(false);
            }
        }
        catch (Exception ex)
        {
            // handle exceptions
        }
        finally
        {
            // delete temporary folder once done
            if (Directory.Exists(tempFolder)) 
            { 
                Directory.Delete(tempFolder, true); 
            }
        }
    }  
}

我建议从立即释放代码中的所有底层COM对象开始。为此,你需要使用System.Runtime.InteropServices.Marshal.ReleaseComObject来释放一个Outlook对象。然后在Visual Basic中设置一个变量为Nothing (c#中为null)来释放对对象的引用。在系统地释放对象文章中了解更多。

例如,我注意到以下属性和方法调用链:
  foreach (string itemPath in paths)
    {
        oMailItem.Attachments.Add(itemPath);
    }

MailItem类的Attachments属性从OOM返回相应类的实例。并应在。

Attachments类的Add方法返回一个表示新附件的Attachment对象。所以,它也应该被释放