Send GridView Data As Mail Using C#

Sometimes from a software or a Web Application, we need to send some data to the user like reports as mail. Here, I am going to explain how you can send the data displayed in GridView in a table format from C# code .

  1. Create a Windows form project from C# template and add Windows Form. Give the name as SendEmail, add one GridView control and a button to it, as shown below.



  2. Create a table and add data to it. The script is shown below.
    1. Go  
    2. Create database db_Test  
    3. Go  
    4. CREATE TABLE Student(  
    5.     [Name][nvarchar](50) NULL, [DOB][dateNULL, [Email][nvarchar](150) NULL, [Mob][nvarchar](50) NULL)  
    6. Go  
    7. INSERT[Student]([Name], [DOB], [Email], [Mob]) VALUES(N 'a'CAST(N '1990-01-01'  
    8.     AS Date), N '[email protected]', N '555555555')  
    9. INSERT[dbo].[Student]([Name], [DOB], [Email], [Mob]) VALUES(N 'b'CAST(N '1990-04-04'  
    10.     AS Date), N '[email protected]', N '777777777')  
    11. INSERT[dbo].[Student]([Name], [DOB], [Email], [Mob]) VALUES(N 'c'CAST(N '1992-05-08'  
    12.     AS Date), N '[email protected]', N '88888888')  
  3. Select and get this student data into GridView from formload, as shown below.
    1. private void SendEmail_Load(object sender, EventArgs e)  
    2. {  
    3.     SqlConnection sqlConnection = new SqlConnection();  
    4.     sqlConnection.ConnectionString = "server = ServerName; database = dbName; User ID = sa; Password =****"//Connection Details   
    5.     //select fields to mail example student details   
    6.     SqlCommand sqlCommand = new SqlCommand("select Name,DOB,Email,Mob from Student", sqlConnection); //select query command  
    7.     SqlDataAdapter sqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();  
    8.     sqlDataAdapter.SelectCommand = sqlCommand; //add selected rows to sql data adapter  
    9.     DataSet dataSetStud = new DataSet(); //create new data set  
    10.     try {  
    11.         sqlDataAdapter.Fill(dataSetStud, "student"); //fill sql data adapter rows to data set  
    12.         dgStudent.ColumnCount = 4;  
    13.         dgStudent.Columns[0].HeaderText = "Student Name";  
    14.         dgStudent.Columns[0].DataPropertyName = "Name";  
    15.         dgStudent.Columns[1].HeaderText = "Date of birth";  
    16.         dgStudent.Columns[1].DataPropertyName = "DOB";  
    17.         dgStudent.Columns[2].HeaderText = "Mail Id";  
    18.         dgStudent.Columns[2].DataPropertyName = "Email";  
    19.         dgStudent.Columns[3].HeaderText = "Mobile No";  
    20.         dgStudent.Columns[3].DataPropertyName = "Mob";  
    21.         dgStudent.DataSource = dataSetStud;  
    22.         dgStudent.DataMember = "student";  
    23.     } catch (Exception Ex) {  
    24.         System.Windows.Forms.MessageBox.Show(Ex.Message);  
    25.         sqlConnection.Close();  
    26.     }  
    27. }  
  4. Create a function, which accepts GridView and returns HTML table, as shown below.
    1. public static string getHtml(DataGridView grid) {  
    2.     try {  
    3.         string messageBody = "<font>The following are the records: </font><br><br>";  
    4.         if (grid.RowCount == 0) return messageBody;  
    5.         string htmlTableStart = "<table style=\"border-collapse:collapse; text-align:center;\" >";  
    6.         string htmlTableEnd = "</table>";  
    7.         string htmlHeaderRowStart = "<tr style=\"background-color:#6FA1D2; color:#ffffff;\">";  
    8.         string htmlHeaderRowEnd = "</tr>";  
    9.         string htmlTrStart = "<tr style=\"color:#555555;\">";  
    10.         string htmlTrEnd = "</tr>";  
    11.         string htmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">";  
    12.         string htmlTdEnd = "</td>";  
    13.         messageBody += htmlTableStart;  
    14.         messageBody += htmlHeaderRowStart;  
    15.         messageBody += htmlTdStart + "Student Name" + htmlTdEnd;  
    16.         messageBody += htmlTdStart + "DOB" + htmlTdEnd;  
    17.         messageBody += htmlTdStart + "Email" + htmlTdEnd;  
    18.         messageBody += htmlTdStart + "Mobile" + htmlTdEnd;  
    19.         messageBody += htmlHeaderRowEnd;  
    20.         //Loop all the rows from grid vew and added to html td  
    21.         for (int i = 0; i <= grid.RowCount - 1; i++) {  
    22.             messageBody = messageBody + htmlTrStart;  
    23.             messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[0].Value + htmlTdEnd; //adding student name  
    24.             messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[1].Value + htmlTdEnd; //adding DOB  
    25.             messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[2].Value + htmlTdEnd; //adding Email   
    26.             messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[3].Value + htmlTdEnd; //adding Mobile  
    27.             messageBody = messageBody + htmlTrEnd;  
    28.         }  
    29.         messageBody = messageBody + htmlTableEnd;  
    30.         return messageBody; // return HTML Table as string from this function  
    31.     } catch (Exception ex) {  
    32.         return null;  
    33.     }  
    34. }  
  5. Now, lets create a function to send the mail with this HTML format string as the body of the mail. Before creating this function, add two namespaces given below.
    1. using System.Net;  
    2. using System.Net.Mail;  
    3. The  
    4. function is as follows: public static void Email(string htmlString) {  
    5.     try {  
    6.         MailMessage message = new MailMessage();  
    7.         SmtpClient smtp = new SmtpClient();  
    8.         message.From = new MailAddress("FromMailAddress");  
    9.         message.To.Add(new MailAddress("ToMailAddress"));  
    10.         message.Subject = "Test";  
    11.         message.IsBodyHtml = true//to make message body as html  
    12.         message.Body = htmlString;  
    13.         smtp.Port = 587;  
    14.         smtp.Host = "smtp.gmail.com"//for gmail host  
    15.         smtp.EnableSsl = true;  
    16.         smtp.UseDefaultCredentials = false;  
    17.         smtp.Credentials = new NetworkCredential("FromMailAdrress""password");  
    18.         smtp.DeliveryMethod = SmtpDeliveryMethod.Network;  
    19.         smtp.Send(message);  
    20.     } catch (Exception) {}  
    21. }  
    To use this function given above, you need to pass a string (string, which you wanted in the mail body) to it. Here, in this function, I have configured only for Gmail host. If your “from address” is different from Gmail, then you have to set that Server port number, host name and SSL property. Some Server names are given below.

  6. Server NameSMTP AddressPortSSL
    Yahoo!smtp.mail.yahoo.com587Yes
    GMailsmtp.gmail.com587Yes
    Hotmailsmtp.live.com587Yes

  7. Now, you can use these functions to send GridView data as a mail in button click, as shown below.
    1. private void btnSent_Click(object sender, EventArgs e) {  
    2.     string htmlString = getHtml(dgStudent); //here you will be getting an html string  
    3.     Email(htmlString); //Pass html string to Email function.  
    4. }  
  8. Now, run and click “send as email” button. Check that you will be getting an Email to “to address”, which you provide and the output is shown below.