Friday, August 28, 2026

Gridview to email

 using System;

using System.IO;

using System.Net;

using System.Net.Mail;

using System.Text;

using System.Web.UI;

using System.Web.UI.WebControls;


protected void btnSendEmail_Click(object sender, EventArgs e)

{

    try

    {

        // Convert GridView to HTML

        StringBuilder sb = new StringBuilder();


        using (StringWriter sw = new StringWriter(sb))

        {

            using (HtmlTextWriter hw = new HtmlTextWriter(sw))

            {

                GridView1.RenderControl(hw);

            }

        }


        string gridHtml = sb.ToString();


        // Create email

        MailMessage mail = new MailMessage();


        mail.From = new MailAddress("yourmail@gmail.com");

        mail.To.Add("receiver@gmail.com");


        mail.Subject = "GridView Report";

        mail.Body = @"

            <html>

            <body>

                <h2>GridView Report</h2>

                <p>Please find the report below:</p>

                " + gridHtml + @"

            </body>

            </html>";


        mail.IsBodyHtml = true;


        // SMTP settings

        SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);


        smtp.EnableSsl = true;

        smtp.Credentials = new NetworkCredential(

            "yourmail@gmail.com",

            "YOUR_APP_PASSWORD"

        );


        smtp.Send(mail);


        Response.Write("<script>alert('Email sent successfully');</script>");

    }

    catch (Exception ex)

    {

        Response.Write("<script>alert('" +

            ex.Message.Replace("'", "") +

            "');</script>");

    }

}





Main code 

public override void VerifyRenderingInServerForm(Control control)

{

    // Required for GridView rendering

}


No comments:

Post a Comment

Gridview send email

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; ...