简体   繁体   English

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

[英]Converting a Outlook mail attachment to byte array with C#

Fair warning : I'm a little bit of a rookie to C# and to Outlook, so bear with me on this. 公平警告 :我是C#和Outlook的新手,所以请耐心等待。

I've been experimenting with emails in Outlook for a quick and dirty addin I'm building, but the addin requires me to send attached files to a different system. 我一直在用Outlook中的电子邮件试验我正在构建的快速而脏的插件,但插件需要我将附加文件发送到不同的系统。

Long story short; 长话短说; in order to do this I need to convert an Outlook item's mail attachment into a byte array. 为了做到这一点,我需要将Outlook项目的邮件附件转换为byte数组。

What I have thus far (and the complete code is obviously miles longer than this, but I'm sure we all have better things to do than to sit and read page up and page down of code): 到目前为止我所拥有的(完整的代码显然比这长了几英里,但我确信我们都有更好的事情要做,而不是坐下来阅读页面并向下翻页代码):

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

Problem is, that I have no idea how to convert a to a byte array. 问题是,我不知道如何将a转换为byte数组。

PS: I know there are about a billion answers as to how to convert a byte array to a mail, but none to explain how to get it running the other way around. PS:我知道关于如何将byte数组转换为邮件有大约10亿个答案,但没有解释如何让它以相反的方式运行。

EDIT 1: I would rather not have to save the file. 编辑1:我宁愿不必保存文件。

The second method proposed by Dmitry (open attachment as binary stream) is also achievable in managed code. Dmitry提出的第二种方法(开放附件作为二进制流)也可以在托管代码中实现。 It uses the PropertyAccessor interface, which is available for Attachment objects in C#. 它使用PropertyAccessor接口,该接口可用于C#中的Attachment对象。 Here is some sample code I've used successfully in my own project: 以下是我在自己的项目中成功使用的一些示例代码:

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);

My example code is based on the How to: Modify an Attachment of an Outlook Email Message topic provided by Ken Getz, MCW Technologies, LLC as part of the MSDN documentation . 我的示例代码基于Ken Getz,MCW Technologies,LLC提供的如何:修改Outlook电子邮件附件主题作为MSDN文档的一部分。

You can either 你也可以

  1. Save the attachment ( Attachment.SaveAsFile ) to a file, then open the file as a byte stream. 将附件( Attachment.SaveAsFile )保存到文件,然后将该文件作为字节流打开。
  2. If you were using C++ or Delphi, you could use IAttach::OpenProperty (PR_ATTACH_DATA_BIN, IID_IStream, ..) to open the attachment as IStream COM object. 如果您使用的是C ++或Delphi,则可以使用IAttach :: OpenProperty (PR_ATTACH_DATA_BIN,IID_IStream,..)将附件作为IStream COM对象打开。
  3. If using Redemption is an option, it exposes the AsArray property on the Attachment and RDOAttachment objects. 如果使用Redemption是一个选项,它会在AttachmentRDOAttachment对象上公开AsArray属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM