Finally, the
HTML Table string will be used to send the DataGridView’s data to Email in
Windows Forms (WinForms) Application using C# and VB.Net.
Form Design
The following Form consists of:
DataGridView – For displaying data.
Button – For sending DataGridView to email.
Mail Server Settings in App.Config file
The following Mail Server settings need to be saved in the
App.Config file.
Note: It is necessary to use the sender’s email address credentials while defining the
Gmail SMTP Server Credentials as
Gmail the sender’s email address must be equal to
Gmail Username specified in credentials.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="sender@gmail.com">
<network host="smtp.gmail.com"
port="587"
enableSsl="true"
userName="sender@gmail.com"
password="SenderGmailPassword"
defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
Namespaces
You will need to import the following namespaces.
C#
using System.Net;
using System.Data;
using System.Net.Mail;
using System.Configuration;
using System.Net.Configuration;
VB.Net
Imports System.Net
Imports System.Data
Imports System.Net.Mail
Imports System.Configuration
Imports System.Net.Configuration
MailMessage Class Properties
Following are the required properties of the MailMessage class.
From – Sender’s email address
To – Recipient(s) Email Address
CC – Carbon Copies (if any)
BCC – Blind Carbon Copies (if any)
Subject – Subject of the Email
Body – Body of the Email
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments (if any)
ReplyTo – ReplyTo Email address.
SMTP Class Properties
Following are the properties of the SMTP class.
Host – SMTP Server URL (Gmail: smtp.gmail.com)
EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of to Account used to send emails
Credentials – Valid login credentials for the SMTP server (Gmail: email address and password)
Port – Port Number of the SMTP sever (Gmail: 587)
Populating the DataGridView
Inside the
Form Load event handler, the
DataGridView is populated with data by making use of a dynamic
DataTable with some records.
C#
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country", typeof(string))
});
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
this.dataGridView1.DataSource = dt;
this.dataGridView1.AllowUserToAddRows = false;
}
VB.Net
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn() { New DataColumn("Id", GetType(Integer)),
New DataColumn("Name", GetType(String)),
New DataColumn("Country", GetType(String))})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
Me.dataGridView1.DataSource = dt
Me.dataGridView1.AllowUserToAddRows = False
End Sub
Sending DataGridView to Email in Windows Application
When the
Send Button is clicked, an
HTML Table is created with string concatenation.
If
HTML Table will contain columns same as that of the
DataGridView and then, a FOREACH loop is executed over the
DataGridView columns to add their header texts to the Header row of the
HTMLTable.
Once the Header row is populated then, a FOREACH loop is executed over the
DataGridView rows to add data rows to the
HTML Table.
Next, an object of the MailMessage class is created and the Recipient email address (to), the Sender email address (from), Subject and Body values are set.
Then, object of the
SmtpClient class is created and the settings of the Mail Server such has
Host,
Port,
DefaultCredentials,
EnableSsl,
Username and
Password are fetched from the mailSettings section of the
App.Config file and are set in respective properties of the
SmtpClient class object.
Finally, the email is being sent and success the message is displayed in Message Box.
C#
private void btnSend_Click(object sender, EventArgs e)
{
//Table start.
string html = "<table cellpadding='5' cellspacing='0' style='border: 1px solid #ccc;font-size: 9pt'>";
//Adding HeaderRow.
html += "<tr>";
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
html += "<th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + column.HeaderText + "";
}
html += "</tr>";
//Adding DataRow.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
html += "<tr>";
foreach (DataGridViewCell cell in row.Cells)
{
html += "<td style='width:120px;border: 1px solid #ccc'>" + cell.Value.ToString() + "";
}
html += "</tr>";
}
//Table end.
html += "</table>";
//Read SMTP section from App.Config.
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
//Sending the DataGridView's HTML in Email.
using (MailMessage mm = new MailMessage(smtpSection.From, "recipient@gmail.com"))
{
mm.Subject = "DataGridView";
mm.Body = html;
mm.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = smtpSection.Network.Host;
smtp.Port = smtpSection.Network.Port;
smtp.EnableSsl = smtpSection.Network.EnableSsl;
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials;
smtp.Credentials = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
smtp.Send(mm);
MessageBox.Show("Email sent.", "Message");
}
}
}
VB.Net
Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click
'Table start.
Dim html As String = "<table cellpadding='5' cellspacing='0' style='border: 1px solid #ccc;font-size: 9pt'>"
'Adding HeaderRow.
html &= "<tr>"
For Each column As DataGridViewColumn In dataGridView1.Columns
html &= "<th style='background-color: #B8DBFD;border: 1px solid #ccc'>" & column.HeaderText &"</th>"
Next
html &= "</tr>"
'Adding DataRow.
For Each row As DataGridViewRow In dataGridView1.Rows
html &= "<tr>"
For Each cell As DataGridViewCell In row.Cells
html &= "<td style='width:120px;border: 1px solid #ccc'>" & cell.Value.ToString() & "</td>"
Next
html &= "</tr>"
Next
'Table end.
html &= "</table>"
'Read SMTP section from App.Config.
Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
'Sending the DataGridView's HTML in Email.
Using mm As MailMessage = New MailMessage(smtpSection.From, "recipient@gmail.com")
mm.Subject = "DataGridView"
mm.Body = html
mm.IsBodyHtml = True
Using smtp As SmtpClient = New SmtpClient()
smtp.Host = smtpSection.Network.Host
smtp.Port = smtpSection.Network.Port
smtp.EnableSsl = smtpSection.Network.EnableSsl
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials
smtp.Credentials = New NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password)
smtp.Send(mm)
MessageBox.Show("Email sent.", "Message")
End Using
End Using
End Sub
Screenshot
Downloads