Carel Carel - 3 years ago 164
ASP.NET (C#) Question

Get file to send as attachment from byte array

I have an ASP.NET MVC application that has to send an email to a list of recipients with an attachment detailing a specific "Project". I get the details for this from a report by making use of SQL Server Reporting Services (SSRS).

I've never really used SSRS before, but I received some code from a colleague where he used it. What he does with the report is he downloads it in the browser to the client's machine. So, if I don't do that I sit with a byte array containing the report data.

Is there a way I can send this as an attachment without first physically writing the file to the filesystem of the server? The report will either be in excel format or a pdf.

Edit: I am using

to send the email's.

Answer Source

to do this you would need to leverage off the SSRS ReportManager API as follows.

  1. First read in the report from the Web Service with SSRS
  2. Read the file into memory rather than saving to the server or client
  3. Send the MemoryStream object straight to the email server.

Reporting services: Get the PDF of a generated report How to send an email with attachments using SmtpClient.SendAsync?

string strReportUser = "RSUserName";
string strReportUserPW = "MySecretPassword";
string strReportUserDomain = "DomainName";

string sTargetURL = "http://SqlServer/ReportServer?" +
   "/MyReportFolder/Report1&rs:Command=Render&rs:format=PDF&ReportParam=" +

HttpWebRequest req =
      (HttpWebRequest)WebRequest.Create( sTargetURL );
req.PreAuthenticate = true;
req.Credentials = new System.Net.NetworkCredential(
    strReportUserDomain );

HttpWebResponse HttpWResp = (HttpWebResponse)req.GetResponse();

Stream fStream = HttpWResp.GetResponseStream();


//Now turn around and send this as the response..
ReadFullyAndSend( fStream );

ReadFullyAnd send method. NB: the SendAsync call so your not waiting for the server to send the email completely before you are brining the user back out of the land of nod.

public static void ReadFullyAndSend( Stream input )
   using ( MemoryStream ms = new MemoryStream() )
      input.CopyTo( ms );

        MailMessage message = new MailMessage("", "");
            Attachment attachment = new Attachment(ms, "my attachment",, "application/");
            message.Body = "This is an async test.";

            SmtpClient smtp = new SmtpClient("localhost");
            smtp.Credentials = new NetworkCredential("foo", "bar");
            smtp.SendAsync(message, null);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download