Tuesday, September 10, 2013

Export Crystal Report to PDF and send in Email as Attachment in ASP.Net using C#

I have made use of the following article to create a sample for you.
What I simply did is added a button to the above code to send email and on Button click I am generating PDF and sending email
Namespaces
1
2
3
4
5
6
7
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using CrystalDecisions.CrystalReports.Engine;
using System.Net.Mail;
using System.Net;
using CrystalDecisions.Shared;
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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("sender@gmail.com", "receiver@gmail.com"))
    {
        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 = "sender@gmail.com";
        credential.Password = "xxxxx";
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = credential;
        smtp.Port = 587;
        smtp.EnableSsl = true;
        smtp.Send(mm);
    }
}

No comments:

Post a Comment