使用VSTO转发电子邮件时出现附件问题



我有一个RibbonXML,它提供了一个上下文菜单,可以对收到的电子邮件执行操作。该电子邮件包含一个电子表格附件,我想更新该电子表格(xlsx(并将其转发给另一个收件人。。。

实际情况是,收件人看到两个附件,一个通常很小(几KB(,另一个是正确的附件。这对pdf或文本文件也有同样的作用,所以很确定它不是文件类型。它显示在电子邮件检查器的附件列表中,但如果你试图用它做任何事情,Outlook会说找不到附件。

我从头开始构建测试,并添加解决方案的组件,直到发现错误。它似乎与从新电子邮件项目中删除附件有关(由Forward((方法产生(。

public void OnTestAttachment(Office.IRibbonControl control)
{
if (control.Context is Selection)
{
Selection selection = control.Context as Selection;
if (selection.Count == 1)
{
object item = selection[1];
if (item is MailItem)
{
MailItem mailItem = item as MailItem;
var newItem = mailItem.Forward();
newItem.Recipients.Add("xxxxx@xxxxx.com");
var newAttachments = newItem.Attachments;
// remove the line below and I don't see the issue
for (int i = newAttachments.Count; i >= 1; i--) { newAttachments.Remove(i); }
{
var body = "Testing.....rn";
MSWord.Document document = (MSWord.Document)newItem.GetInspector.WordEditor;
MSWord.Paragraph paragraph = document.Paragraphs.Add(document.Range());
paragraph.Range.Text = body;
}
// do some things with a file..in prod I save the existing file, edit it via code and then save it back down....
// I tested using a byte stream in case that has something to do with the issue (as that's the closest 
// match to what is actually going on in prod)
var fileName = @"C:Users<me>Test.xlsx";
var temp = Path.Combine(Path.GetTempPath(), Path.GetFileName(fileName));
byte[] buffer = File.ReadAllBytes(fileName);
using (var stream = new FileStream(temp, FileMode.Create, FileAccess.Write))
{
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}
newAttachments.Add(temp, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
// the issues doesn't appear here...it is only once it is received that it appears
newItem.Display();
Marshal.ReleaseComObject(newItem);
Marshal.ReleaseComObject(newAttachments);
Marshal.ReleaseComObject(mailItem);
}
}
Marshal.ReleaseComObject(selection);
}

它显示在电子邮件检查器的附件列表中,但如果你试图对它进行任何操作,Outlook会说找不到附件。

Outlook对象模型与所描述的问题无关。文件可以用空数据覆盖,然后可以附加到电子邮件:

using (var stream = new FileStream(temp, FileMode.Create, FileAccess.Write))
{
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}

以下句子证实了这一点:

发生的情况是,收件人看到两个附件,一个通常很小(几KB(,另一个是正确的附件。

如果您需要处理文件内容,我建议使用Attachment类的SaveAsFile方法保存文件,该方法将附件保存到指定的路径。因此,您可以确保文件内容不是空的。

最新更新