从字节数组中获取要作为附件发送的文件

Car*_*rel 6 c# asp.net reporting-services

我有一个ASP.NET MVC应用程序,它必须向收件人列表发送一封电子邮件,其中附件详细说明了特定的"项目".我通过使用SQL Server Reporting Services(SSRS)从报告中获取详细信息.

我之前从未真正使用过SSRS,但是我收到了他使用它的同事的一些代码.他对报告的处理是将其在浏览器中下载到客户端的计算机上.所以,如果我不这样做,我会坐在一个包含报告数据的字节数组中.

有没有一种方法可以将此作为附件发送而无需先将文件物理写入服务器的文件系统?该报告将采用excel格式或pdf格式.

编辑:SmtpClient用来发送电子邮件.

Jos*_*ush 8

获取文件数据 byte[]

byte[] binaryFile = //  get your file data from the SSRS ...
string filename = "SSRS.pdf";
Run Code Online (Sandbox Code Playgroud)

准备目标地址的列表或数组:

string[] addresses = // get addresses somehow (db/hardcoded/config/...)
Run Code Online (Sandbox Code Playgroud)

通过SmtpClient以下方式发送smtp消息:

MailMessage mailMessage= new MailMessage();

mailMessage.From = new MailAddress("sender email address goes here");

// Loop all your clients addresses
foreach (string address in addresses)
{
    mailMessage.To.Add(address);    
}

mailMessage.Subject = "your message subject goes here";
mailMessage.Body = "your message body goes here";

MemoryStream memoryStream = new MemoryStream(binaryFile);
mailMessage.Attachments.Add( new Attachment( memoryStream, filename , MediaTypeNames.Application.Pdf ));

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
Run Code Online (Sandbox Code Playgroud)


Rob*_*ing 4

为此,您需要利用 SSRS ReportManager API,如下所示。

  1. 首先使用 SSRS 读取来自 Web 服务的报告
  2. 将文件读入内存而不是保存到服务器或客户端
  3. 将 MemoryStream 对象直接发送到电子邮件服务器。

报告服务:获取生成报告的 PDF 如何使用 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=" +
   ParamValue;

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

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

Stream fStream = HttpWResp.GetResponseStream();

HttpWResp.Close();



//Now turn around and send this as the response..
ReadFullyAndSend( fStream );
Run Code Online (Sandbox Code Playgroud)

ReadFullyAnd 发送方法。注意:SendAsync 调用使您无需等待服务器完全发送电子邮件即可将用户带回点头之地。

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

        MailMessage message = new MailMessage("from@foo.com", "too@foo.com");
            Attachment attachment = new Attachment(ms, "my attachment",, "application/vnd.ms-excel");
            message.Attachments.Add(attachment);
            message.Body = "This is an async test.";

            SmtpClient smtp = new SmtpClient("localhost");
            smtp.Credentials = new NetworkCredential("foo", "bar");
            smtp.SendAsync(message, null);
   }
}  
Run Code Online (Sandbox Code Playgroud)