Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Outlook mail attachment to byte array with C#

Tags:

c#

email

outlook

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.

like image 422
ViRALiC Avatar asked Apr 28 '15 06:04

ViRALiC


2 Answers

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.

like image 192
IRQ Avatar answered Nov 10 '22 19:11

IRQ


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 (I am its author), it exposes the AsArray property on the Attachment and RDOAttachment objects.
like image 24
Dmitry Streblechenko Avatar answered Nov 10 '22 19:11

Dmitry Streblechenko