简体   繁体   中英

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.

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.

Long story short; in order to do this I need to convert an Outlook item's mail attachment into a byte array.

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.

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.

EDIT 1: I would rather not have to save the file.

The second method proposed by Dmitry (open attachment as binary stream) is also achievable in managed code. It uses the PropertyAccessor interface, which is available for Attachment objects in C#. 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 .

You can either

  1. Save the attachment ( Attachment.SaveAsFile ) to a file, then open the file as a byte stream.
  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.
  3. If using Redemption is an option, it exposes the AsArray property on the Attachment and RDOAttachment objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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