Reputation: 527
We receive files from various entities that can contain MIME parts (which are PDFs) in them that are base64 encoded. We extract it out and store it to open later. This has worked fine for all but from one of the entities. Their files will save, but have not been able to open them.
Here is the code:
public byte[] GetAttachmentByName(string name)
{
foreach (var attachment in _mimeMessage.BodyParts.OfType<MimePart>())
{
if (attachment.ContentId != name)
continue;
using (var stream = new System.IO.MemoryStream())
{
using (var filtered = new FilteredStream(stream))
{
filtered.Add(DecoderFilter.Create("base64"));
attachment.ContentObject.DecodeTo(filtered);
return stream.ToArray();
}
}
}
return null;}
Here is what part of the MIME looks like:
MIME-Version: 1.0 Content-Type: multipart/related; boundary="=-antAW7IrKfe1DvH3559M9g=="
…
--=-antAW7IrKfe1DvH3559M9g== Content-Type: application/pdf Content-Transfer-Encoding: base64 Content-Description: Content-Id: "AC13127925.pdf"
…
bGVyDTw8IA0vU2l6ZSAxODkgDS9Sb290IDE4OCAwIFIgDS9JbmZvIDEgMCBSIA0+PiANc3Rh cnR4cmVmDTU3MzU3MiANJSVFT0YN
--=-antAW7IrKfe1DvH3559M9g==--
(I included the start, middle, and end of the MIME part. There is also XML in another part of the file, but that is processing just fine. The problem we are having is with the MIME/PDF.)
Any guidance at all is appreciated.
Upvotes: 1
Views: 2526
Reputation: 38538
The MimeContent.DecodeTo()
method already decodes the base64 for you, so you need to change your code to this:
public byte[] GetAttachmentByName(string name)
{
foreach (var attachment in _mimeMessage.BodyParts.OfType<MimePart>())
{
if (attachment.ContentId != name)
continue;
using (var stream = new System.IO.MemoryStream())
{
attachment.ContentObject.DecodeTo(filtered);
return stream.ToArray();
}
}
return null;
}
Upvotes: 4