Send Email in C#

Sending emails from a Windows or Web application has become quite normal these days. Some common examples of emails are sending messages, errors, updates, user reports, analytics, or an attachment. What about sending a report that contains the records displayed in a control?

In this article, I'm going to explain how you can send the data displayed in GridView in a table format in an email using C#. This code can be used in any any desktop or Web application. In our case, I'm going to create a Windows Forms application.
Step 1. Create a Client
Create a Windows Forms project in Visual Studio using C# template. Name it SendEmail, add a GridView control to the form. Also add a Button control as shown below.
Step 2. Email Database
We're going to store our emails in a SQL Server backend database.
In your SQL Server, create a database table and add data to it. The script is shown below. This script creates a new SQL Server database named db_Test and creates a new table Student with some records. A student record includes Name, DOB, Email, and Mob. 
    1. Go
    2. Create database db_Test
    3. Go
    4. CREATE TABLE Student(
    5. [Name][nvarchar](50) NULL, [DOB][date] NULL, [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 '', N '555555555')
    9. INSERT[dbo].[Student]([Name], [DOB], [Email], [Mob]) VALUES(N 'b', CAST(N '1990-04-04'
    10. AS Date), N '', N '777777777')
    11. INSERT[dbo].[Student]([Name], [DOB], [Email], [Mob]) VALUES(N 'c', CAST(N '1992-05-08'
    12. AS Date), N '', N '88888888')
Step 3. Load data from database
Select and get the student data and load into the GridView control. Write the following code on your Form's load event handler. This code creates a connection to out newly created database, You will have to change the connection string. Reads data and binds it to the GridView control.
  1. private void SendEmail_Load(object sender, EventArgs e) {  
  2.     SqlConnection sqlConnection = new SqlConnection();  
  3.     sqlConnection.ConnectionString = "server = YOURSERVERNAME; database = YOURDBNAME; User ID = sa; Password = YOURPASSWORD"//Connection Details  
  4.     //select fields to mail example student details  
  5.     SqlCommand sqlCommand = new SqlCommand("select Name,DOB,Email,Mob from Student", sqlConnection); //select query command  
  6.     SqlDataAdapter sqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();  
  7.     sqlDataAdapter.SelectCommand = sqlCommand; //add selected rows to sql data adapter  
  8.     DataSet dataSetStud = new DataSet(); //create new data set  
  9.     try {  
  10.         sqlDataAdapter.Fill(dataSetStud, "student"); //fill sql data adapter rows to data set  
  11.         dgStudent.ColumnCount = 4;  
  12.         dgStudent.Columns[0].HeaderText = "Student Name";  
  13.         dgStudent.Columns[0].DataPropertyName = "Name";  
  14.         dgStudent.Columns[1].HeaderText = "Date of birth";  
  15.         dgStudent.Columns[1].DataPropertyName = "DOB";  
  16.         dgStudent.Columns[2].HeaderText = "Mail Id";  
  17.         dgStudent.Columns[2].DataPropertyName = "Email";  
  18.         dgStudent.Columns[3].HeaderText = "Mobile No";  
  19.         dgStudent.Columns[3].DataPropertyName = "Mob";  
  20.         dgStudent.DataSource = dataSetStud;  
  21.         dgStudent.DataMember = "student";  
  22.     } catch (Exception Ex) {  
  23.         System.Windows.Forms.MessageBox.Show(Ex.Message);  
  24.         sqlConnection.Close();  
  25.     }  
  26. }  
Step 4. Create HTML Email Template
Create a function, which accepts GridView data and returns HTML table, as shown below. HTML is a common way to format and send an email in a formatted form that can easily be read as an email. 
This following code creates an email template that is how the email will look like in HTML format.
  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. }  
Step 5. Send email using SMTP 
Now, let's create a method to send an email  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;
The Email method is listed below. As you can see from the below code, the method Email takes HTML as a string. A new MailMessage is created with From, To and other properties. SmtpClient is created with a Port, Host, and other properties. In the end, the Send method is used to send the email.
  1. public static void Email(string htmlString) {  
  2.     try {  
  3.         MailMessage message = new MailMessage();  
  4.         SmtpClient smtp = new SmtpClient();  
  5.         message.From = new MailAddress("FromMailAddress");  
  6.         message.To.Add(new MailAddress("ToMailAddress"));  
  7.         message.Subject = "Test";  
  8.         message.IsBodyHtml = true//to make message body as html  
  9.         message.Body = htmlString;  
  10.         smtp.Port = 587;  
  11.         smtp.Host = ""//for gmail host  
  12.         smtp.EnableSsl = true;  
  13.         smtp.UseDefaultCredentials = false;  
  14.         smtp.Credentials = new NetworkCredential("FromMailAddress""password");  
  15.         smtp.DeliveryMethod = SmtpDeliveryMethod.Network;  
  16.         smtp.Send(message);  
  17.     } catch (Exception) {}  
  18. }  
Step 6. Email SMTP Settings
Email 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 uses the Gmail host only. 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! 587 Yes
    GMail 587 Yes
    Hotmail 587 Yes

Step 7. Send email
Now, let's use these functions to send GridView data as an email on a 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. }  
Step 8. Build and run
Now, run and click “send an email” button. Check that you will be getting an Email to “to address”, which you provide and the output is shown below.

In this article, I built a Windows application that demonstrated how to create a working application in C# to send emails with data in the email.