I am making an application where I have to generate a report with Crystal Reports and send it by email. Would anyone have some way to do this? Sending and generating reports are already working, but I'm not able to convert and send them to email.
I am making an application where I have to generate a report with Crystal Reports and send it by email. Would anyone have some way to do this? Sending and generating reports are already working, but I'm not able to convert and send them to email.
I found it here, maybe it helps
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using CrystalDecisions.CrystalReports.Engine;
using System.Net.Mail;
using System.Net;
using CrystalDecisions.Shared;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("~/CustomerReport.rpt"));
Customers dsCustomers = GetData("select * from customers");
crystalReport.SetDataSource(dsCustomers);
CrystalReportViewer1.ReportSource = crystalReport;
}
}
private Customers GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (Customers dsCustomers = new Customers())
{
sda.Fill(dsCustomers, "DataTable1");
return dsCustomers;
}
}
}
}
protected void ExportAndEmail(object sender, EventArgs e)
{
ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("~/CustomerReport.rpt"));
Customers dsCustomers = GetData("select * from customers");
crystalReport.SetDataSource(dsCustomers);
using (MailMessage mm = new MailMessage("[email protected]", "[email protected]"))
{
mm.Subject = "Crystal Report PDF example";
mm.Body = "Crystal Report PDF example";
mm.Attachments.Add(new Attachment(crystalReport.ExportToStream(ExportFormatType.PortableDocFormat), "Report.pdf"));
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
NetworkCredential credential = new NetworkCredential();
credential.UserName = "[email protected]";
credential.Password = "xxxxx";
smtp.UseDefaultCredentials = true;
smtp.Credentials = credential;
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Send(mm);
}
}