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 .
- 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.
- Create a table and add data to it. The script is shown below.
- Go
- Create database db_Test
- Go
- CREATE TABLE Student(
- [Name][nvarchar](50) NULL, [DOB][date] NULL, [Email][nvarchar](150) NULL, [Mob][nvarchar](50) NULL)
- Go
- INSERT[Student]([Name], [DOB], [Email], [Mob]) VALUES(N 'a', CAST(N '1990-01-01'
- AS Date), N '[email protected]', N '555555555')
- INSERT[dbo].[Student]([Name], [DOB], [Email], [Mob]) VALUES(N 'b', CAST(N '1990-04-04'
- AS Date), N '[email protected]', N '777777777')
- INSERT[dbo].[Student]([Name], [DOB], [Email], [Mob]) VALUES(N 'c', CAST(N '1992-05-08'
- AS Date), N '[email protected]', N '88888888')
- Select and get this student data into GridView from formload, as shown below.
- private void SendEmail_Load(object sender, EventArgs e)
- {
- SqlConnection sqlConnection = new SqlConnection();
- sqlConnection.ConnectionString = "server = VSBS01; database = dbHRVeniteck; User ID = sa; Password = veniteck@2016";
-
- SqlCommand sqlCommand = new SqlCommand("select Name,DOB,Email,Mob from Student", sqlConnection);
- SqlDataAdapter sqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
- sqlDataAdapter.SelectCommand = sqlCommand;
- DataSet dataSetStud = new DataSet();
- try {
- sqlDataAdapter.Fill(dataSetStud, "student");
- dgStudent.ColumnCount = 4;
- dgStudent.Columns[0].HeaderText = "Student Name";
- dgStudent.Columns[0].DataPropertyName = "Name";
- dgStudent.Columns[1].HeaderText = "Date of birth";
- dgStudent.Columns[1].DataPropertyName = "DOB";
- dgStudent.Columns[2].HeaderText = "Mail Id";
- dgStudent.Columns[2].DataPropertyName = "Email";
- dgStudent.Columns[3].HeaderText = "Mobile No";
- dgStudent.Columns[3].DataPropertyName = "Mob";
- dgStudent.DataSource = dataSetStud;
- dgStudent.DataMember = "student";
- } catch (Exception Ex) {
- System.Windows.Forms.MessageBox.Show(Ex.Message);
- sqlConnection.Close();
- }
- }
- Create a function, which accepts GridView and returns HTML table, as shown below.
- public static string getHtml(DataGridView grid) {
- try {
- string messageBody = "<font>The following are the records: </font><br><br>";
- if (grid.RowCount == 0) return messageBody;
- string htmlTableStart = "<table style=\"border-collapse:collapse; text-align:center;\" >";
- string htmlTableEnd = "</table>";
- string htmlHeaderRowStart = "<tr style=\"background-color:#6FA1D2; color:#ffffff;\">";
- string htmlHeaderRowEnd = "</tr>";
- string htmlTrStart = "<tr style=\"color:#555555;\">";
- string htmlTrEnd = "</tr>";
- string htmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">";
- string htmlTdEnd = "</td>";
- messageBody += htmlTableStart;
- messageBody += htmlHeaderRowStart;
- messageBody += htmlTdStart + "Student Name" + htmlTdEnd;
- messageBody += htmlTdStart + "DOB" + htmlTdEnd;
- messageBody += htmlTdStart + "Email" + htmlTdEnd;
- messageBody += htmlTdStart + "Mobile" + htmlTdEnd;
- messageBody += htmlHeaderRowEnd;
-
- for (int i = 0; i <= grid.RowCount - 1; i++) {
- messageBody = messageBody + htmlTrStart;
- messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[0].Value + htmlTdEnd;
- messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[1].Value + htmlTdEnd;
- messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[2].Value + htmlTdEnd;
- messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[3].Value + htmlTdEnd;
- messageBody = messageBody + htmlTrEnd;
- }
- messageBody = messageBody + htmlTableEnd;
- return messageBody;
- } catch (Exception ex) {
- return null;
- }
- }
- 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.
- using System.Net;
- using System.Net.Mail;
- The
- function is as follows: public static void Email(string htmlString) {
- try {
- MailMessage message = new MailMessage();
- SmtpClient smtp = new SmtpClient();
- message.From = new MailAddress("FromMailAddress");
- message.To.Add(new MailAddress("ToMailAddress"));
- message.Subject = "Test";
- message.IsBodyHtml = true;
- message.Body = htmlString;
- smtp.Port = 587;
- smtp.Host = "smtp.gmail.com";
- smtp.EnableSsl = true;
- smtp.UseDefaultCredentials = false;
- smtp.Credentials = new NetworkCredential("FromMailAdrress", "password");
- smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
- smtp.Send(message);
- } catch (Exception) {}
- }
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.
Server Name | SMTP Address | Port | SSL |
Yahoo! | smtp.mail.yahoo.com | 587 | Yes |
GMail | smtp.gmail.com | 587 | Yes |
Hotmail | smtp.live.com | 587 | Yes |
- Now, you can use these functions to send GridView data as a mail in button click, as shown below.
- private void btnSent_Click(object sender, EventArgs e) {
- string htmlString = getHtml(dgStudent);
- Email(htmlString);
- }
- 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.