Saturday, 28 April 2012

MAIL GRID VIEW USING ASP.NET

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.IO;
using System.Text;

public partial class Csharp : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }


    public void fn_AttachGrid()

    {

        StringWriter stw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(stw);

        GridView1.RenderControl(hw);

        MailMessage mail = new MailMessage();

        mail.IsBodyHtml = true;

        mail.To.Add(new MailAddress("toMail@domain.com"));

        mail.Subject = "Sales Report";

        System.Text.Encoding Enc = System.Text.Encoding.ASCII;

        byte[] mBArray = Enc.GetBytes(stw.ToString());

        System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);

        mail.Attachments.Add(new Attachment(mAtt, "sales.xls"));

        mail.Body = "Hi PFA";

        SmtpClient smtp = new SmtpClient();

        mail.From = new MailAddress("fromMail@domain.com", "Your Name");

        smtp.Host = "mail.domain.com";

        smtp.UseDefaultCredentials = false;

        smtp.Credentials = new System.Net.NetworkCredential(@"Username", "Password");

        smtp.EnableSsl = true;

        smtp.Send(mail);

        lbldisplay.Text = "Email Sent";

    }

    public override void VerifyRenderingInServerForm(Control control)

    {

    }


    protected void btnSendMail_Click(object sender, EventArgs e)

    {
fn_AttachGrid();

    }

}

No comments:

Post a Comment

back to top