2009-05-28 63 views
5

Estoy tratando de enviar informes desde sql reportserver 2008 como archivo adjunto de correo electrónico utilizando ASP.NET y C#, Hasta ahora he aprendido cómo Get report as PDF en mi código, ahora quiero combinar la línea de códigos comoEnviar informe SQL en archivos adjuntos de correo electrónico utilizando C# y ASP.NET

byte[] bytes = rview.ServerReport.Render(format, deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings); 
Response.OutputStream.Write(bytes, 0, bytes.Length); 
Attachment reportAttachment = new Attachment(Response.OutputStream.Write(bytes,0,bytes.Length),"ado"); //Here I go wrong 

Gracias de antemano

Respuesta

3

Tal vez conseguir este mal (que sé poco sobre SSRS), pero creo que deberías

  1. guardar el archivo en el sistema de archivos

    System.IO.File.WriteAllBytes("c:\temp\temp.pdf", bytes); 
    
  2. enviar el archivo por correo electrónico

    MailMessage mail = new MailMessage(); 
    mail.From  = "Me"; 
    mail.To   = "You"; 
    mail.Subject  = "Subject"; 
    mail.Body  = "Body"; 
    mail.BodyFormat = MailFormat.Html; 
    mail.Attachments.Add(new MailAttachment("c:\temp\temp.pdf")); 
    
    try 
    { 
        SmtpMail.Send(mail); 
    } 
    catch(Exception ex) 
    { 
        Response.Write("Ouch! " + ex.Message); 
    } 
    
+0

Gracias System.IO funciona como encanto, Sólo un pequeño comentario, abetos argumento es la dirección de Cadena de archivo y el segundo es el byte []. De cualquier forma ahora tengo una idea para hacer un servicio web para hacer este trabajo, ¿Será tan difícil y diferente que hacer solo la página web de muestra – adopilot

+0

Tienes razón! Corregí la respuesta. –

13

lugar de guardar el pdf al sistema de archivos en primer lugar, usted podría tratar de utilizar el byte [] volver del servidor de informes y adjuntar la siguiente:

MemoryStream ms = new MemoryStream(bytes); 
mail.Attachments.Add(new Attachment(ms, "temp.pdf")); 

Para una chapuza rápida en una de mis informes hice lo siguiente:

WebClient client = new WebClient(); 
byte[] bytes = client.DownloadData("http://localhost/ReportServer/Pages/ReportViewer.aspx? *** report name *** &rs%3aFormat=PDF"); 
MemoryStream ms = new MemoryStream(bytes); 
mail.Attachments.Add(new Attachment(ms, "temp.pdf")); 

la esperanza que esto sea útil

+0

Adjuntar sin guardar el archivo en el sistema de archivos es una solución mucho más elegante, en mi opinión. Gracias por la solución. – Mozy

+1

Esto funciona bien, aunque tuve que usar System.Net.Mail para poder crear el archivo adjunto desde un MemoryStream. – openshac

1

También podría usar SSRS suscripciones. Tiene funcionalidad de correo electrónico incorporada.

Requisitos:

  • usted tiene su informe estableció.
  • Tiene su Servidor de informes SSRS configurado para enviar correos electrónicos.
  • Su servidor SSRS es 2010 o posterior. No estoy seguro si 2008 y antes suscripciones de soporte.

Microsoft's documentation from the UI standpoint

Código:

var service = new ReportingService2010(); 
service.Url = reportServiceURL; 
service.Credentials = new NetworkCredential(userName, password, domain); 

var reportPath = "your/report/location"; 

string report = $"{reportPath}YourReportName.rdl"; 
string fileName = $"Your Custom Report"; 

//If your report requires input parameters, specify them in an array. 
ParameterValue[] reportParameters = new ParameterValue[1]; 

reportParameters[0] = new ParameterValue(); 
reportParameters[0].Name = "ID"; 
reportParameters[0].Value = ID.ToString(); 

ParameterValue[] extensionParams = new ParameterValue[11];//Adjust this if you omit parameters. 

extensionParams[0] = new ParameterValue(); 
extensionParams[0].Name = "TO"; 
extensionParams[0].Value = "[email protected];[email protected];[email protected];" 

//CC, can be omitted. 
extensionParams[1] = new ParameterValue(); 
extensionParams[1].Name = "CC"; 
extensionParams[1].Value = "[email protected];[email protected];" 

//BCC, can be omitted. 
extensionParams[2] = new ParameterValue(); 
extensionParams[2].Name = "BCC"; 
extensionParams[2].Value = "[email protected];[email protected];" 

//Reply to, where replies should go. 
extensionParams[3] = new ParameterValue(); 
extensionParams[3].Name = "ReplyTo"; 
extensionParams[3].Value = "[email protected]" 

//Include report as an attachment, this should be TRUE. 
extensionParams[4] = new ParameterValue(); 
extensionParams[4].Name = "IncludeReport"; 
extensionParams[4].Value = "True" 

//What you want the attached file to render as. You have some options. 
extensionParams[5] = new ParameterValue(); 
extensionParams[5].Name = "RenderFormat"; 
extensionParams[5].Value = "PDF"; //pdf 
//extensionParams[5].Value = "WORD"; //doc, word 2003 - 2007 
//extensionParams[5].Value = "WORDOPENXML"; //docx, word 2010 - 2013+ 
//extensionParams[5].Value = "EXCEL"; //xls, excel 2003 - 2007 
//extensionParams[5].Value = "EXCELOPENXML"; //xlsx, excel 2010 - 2013+ 
//extensionParams[5].Value = "IMAGE"; //TIFF file 
//extensionParams[5].Value = "CSV"; //CSV file 
//extensionParams[5].Value = "XML"; //XML file 

//Optional, set the priority of the message. 
extensionParams[6] = new ParameterValue(); 
extensionParams[6].Name = "Priority"; 
extensionParams[6].Value = "High"; 
//extensionParams[6].Value = "Normal"; 
//extensionParams[6].Value = "Low"; 

//Subject Line 
extensionParams[7] = new ParameterValue(); 
extensionParams[7].Name = "Subject"; 
extensionParams[7].Value = "Your lovely report"; 

//Comment, I believe this is the "body" of the email. 
extensionParams[8] = new ParameterValue(); 
extensionParams[8].Name = "Comment"; 
extensionParams[8].Value = "Hi there, <br/><br/>I have your report. Thanks for automating me out of the job, you programmer you!"; 

//Include a hyperlink to run the report in the email body? Can be omitted. 
extensionParams[9] = new ParameterValue(); 
extensionParams[9].Name = "IncludeLink"; 
extensionParams[9].Value = "False"; 

//If you want to send it "on behalf of" someone, use this. Can be omitted. 
extensionParams[10] = new ParameterValue(); 
extensionParams[10].Name = "SendEmailToUserAlias"; 
extensionParams[10].Value = "[email protected]"; 

ExtensionSettings extSettings = new ExtensionSettings(); 
extSettings.ParameterValues = extensionParams; 
extSettings.Extension = "Report Server Email"; 

//FYI date must be in ISO 8601 format. This sets it to one minute from now, and will only run once. 
string matchData = $"<ScheduleDefinition><StartDateTime>{DateTime.Now.AddMinutes(1).ToString("s")}</StartDateTime></ScheduleDefinition>"; 

reportingService.CreateSubscription(reportName, extSettings, fileName, "TimedSubscription", matchData, reportParameters); 
Cuestiones relacionadas