使用 C# 将 Outlook 邮件附件转换为字节数组

Converting a Outlook mail attachment to byte array with C#

中肯警告:我是C#和Outlook的新手,所以请多多包涵。

我一直在尝试在 Outlook 中使用电子邮件来构建我正在构建的快速而肮脏的插件,但该插件要求我将附件发送到不同的系统。

长话短说;为此,我需要将 Outlook 项目的邮件附件转换为 byte 数组。

到目前为止我所拥有的(完整的代码显然比这要长很多英里,但我相信我们都有更好的事情要做,而不是坐下来阅读代码的上下一页):

Outlook.Selection sel = control.Context as Outlook.Selection;
Outlook.MailItem mail = sel[1];
Outlook.Attachment a = mail.Attachments[0];

问题是,我不知道如何将 a 转换为 byte 数组。

PS: 我知道关于如何将 byte 数组转换为邮件有大约十亿个答案,但是 none 解释如何得到它 运行 相反。

编辑 1: 我不想保存文件。

你可以

  1. 将附件 (Attachment.SaveAsFile) 保存到文件,然后以字节流形式打开文件。
  2. 如果您使用的是 C++ 或 Delphi,您可以使用 IAttach::OpenProperty(PR_ATTACH_DATA_BIN, IID_IStream, ..) 将附件作为 IStream COM 对象打开。
  3. 如果使用 Redemption is an option (I am its author), it exposes the AsArray property on the Attachment and RDOAttachment 个对象。

Dmitry 提出的第二种方法(打开附件作为二进制流)在托管代码中也是可以实现的。它使用 PropertyAccessor 接口,该接口可用于 C# 中的附件对象。这是我在自己的项目中成功使用的一些示例代码:

const string PR_ATTACH_DATA_BIN = "http://schemas.microsoft.com/mapi/proptag/0x37010102";

Outlook.Attachment attachment = mail.Attachments[0];  

// Retrieve the attachment as a byte array
var attachmentData =
    attachment.PropertyAccessor.GetProperty(PR_ATTACH_DATA_BIN);

我的示例代码基于 如何:修改 Outlook 电子邮件消息的附件 主题 Ken Getz, MCW Technologies, LLC 作为 MSDN documentation.

的一部分