HttpResponseMessage.Content as an attachment for an email

1.7k views Asked by At

I have an API that returns an '.xls' file, using HttpResponseMessage. What I am trying to do is to get that file and attach it to an email that I am sending.

Please keep in mind that I can't change the API implementation, so, the response will always be HtppResponseMessage.

1

There are 1 answers

0
Marius Popa On BEST ANSWER

Well, apparently there is a solution for my problem. What I had to do was to get the HttpContent from the API's HttpResponseMessage as Stream. After that, all the process was a piece of cake.

Here is the solution. It works great.

HttpResponseMessage response = _service.GetAPIResponse(...);
Stream data = response.Content.ReadAsStreamAsync().Result;

var mailMessage = new MailMessage()
mailMessage.Attachments.Add(new Attachment(data, response.Content.Headers.ContentDisposition.FileName));

I hope that this helps someone else as well.

Cheers.