Convert Outlook mail attachment to byte array using C #
Fair warning: I'm a bit new to C#
and at Outlook, so bear with me on that.
I experimented with email messages in Outlook for a quick and dirty add that I create, but add requires me to send attachments to another system.
Shortly speaking; for this I need to convert the nested Outlook app to an array byte
.
What I have so far (and the complete code is obviously much longer than this, but I'm sure we all have all we need to do than sit and read page up and page down):
Outlook.Selection sel = control.Context as Outlook.Selection;
Outlook.MailItem mail = sel[1];
Outlook.Attachment a = mail.Attachments[0];
The problem is I have no idea how to convert a
to an array byte
.
PS: I know there are about a billion answers on how to convert an array byte
to mail, but no one explains how to make it work the other way around. p>
EDIT 1: I would rather not save the file.
source to share
The second method suggested by Dmitry (open attachment as a binary stream) is also implemented in managed code. It uses the PropertyAccessor interface that is available for Attachment objects in C #. Here is some sample code that I have successfully used in my 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 How To: Modify an Outlook Email Attachment , provided by Ken Getz, MCW Technologies, LLC as part of the MSDN Documentation .
source to share
You can either
- Save the attachment ( Attachment.SaveAsFile ) to a file, then open the file as a byte stream.
- If you've been using C ++ or Delphi, you can use IAttach :: OpenProperty (PR_ATTACH_DATA_BIN, IID_IStream, ..) to open the attachment as an IStream COM Object.
- If using Redemption it exposes AsArray property on Attachment and RDOAttachment .
source to share