From Zero to Email Hero: A Beginner's Guide to Sending Email in C#

Do you want to send an email from your C# application? It can be a Windows Forms, ASP.NET, or Blazor application, same C# code can be used to send emails. In this article, learn how to send emails in C#. We will first create a Windows application with a GridView in a table format with emails. The application reads email addresses and sends emails to the listed email addresses using C#.

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. I know Windows Forms is an older technology. You can also create an ASP.NET or Blazor application. 

Step 2. Create an 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. 

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')

Step 3. Load emails 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. The following code reads data and binds it to the GridView control.

private void SendEmail_Load(object sender, EventArgs e) {  
    SqlConnection sqlConnection = new SqlConnection();  
    sqlConnection.ConnectionString = "server = YOURSERVERNAME; database = YOURDBNAME; User ID = sa; Password = YOURPASSWORD"; //Connection Details  
    //select fields to mail example student details  
    SqlCommand sqlCommand = new SqlCommand("select Name,DOB,Email,Mob from Student", sqlConnection); //select query command  
    SqlDataAdapter sqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();  
    sqlDataAdapter.SelectCommand = sqlCommand; //add selected rows to sql data adapter  
    DataSet dataSetStud = new DataSet(); //create new data set  
    try {  
        sqlDataAdapter.Fill(dataSetStud, "student"); //fill sql data adapter rows to data set  
        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();  
    }  
}  

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.

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;  
        //Loop all the rows from grid vew and added to html td  
        for (int i = 0; i <= grid.RowCount - 1; i++) {  
            messageBody = messageBody + htmlTrStart;  
            messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[0].Value + htmlTdEnd; //adding student name  
            messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[1].Value + htmlTdEnd; //adding DOB  
            messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[2].Value + htmlTdEnd; //adding Email  
            messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[3].Value + htmlTdEnd; //adding Mobile  
            messageBody = messageBody + htmlTrEnd;  
        }  
        messageBody = messageBody + htmlTableEnd;  
        return messageBody; // return HTML Table as string from this function  
    } catch (Exception ex) {  
        return null;  
    }  
}  

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.

using System.Net;
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.

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; //to make message body as html  
        message.Body = htmlString;  
        smtp.Port = 587;  
        smtp.Host = "smtp.gmail.com"; //for gmail host  
        smtp.EnableSsl = true;  
        smtp.UseDefaultCredentials = false;  
        smtp.Credentials = new NetworkCredential("FromMailAddress", "password");  
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;  
        smtp.Send(message);  
    } catch (Exception) {}  
}  

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! smtp.mail.yahoo.com 587 Yes
GMail smtp.gmail.com 587 Yes
Hotmail smtp.live.com 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.

private void btnSent_Click(object sender, EventArgs e) {  
    string htmlString = getHtml(dgStudent); //here you will be getting an html string  
    Email(htmlString); //Pass html string to Email function.  
}  

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.
 

Summary

In this article, we learned how to build an email client app in C#, store emails in a database, read emails, and send emails to the email addressed listed in the database. 


Recommended Free Ebook
Similar Articles