Home Asp.net How to Send Asp.net GridView Data in smtp Mail in Asp.net C#...

How to Send Asp.net GridView Data in smtp Mail in Asp.net C# Vb.net

3
0

Now here in this tutorial, I’ll explain how you can send asp .net gridview data in mail/email with its data in asp.net, c#, vb.net using Gmail smtp settings.

In my previous tutorials, I’d explained how to send test mail using gmail smtp settings, how to export gridview selected rows to word excel text and pdf, how to send html web page as email and other more cracking tutorials on Asp.net, JavaScript, jQuery here.

 

The .NET framework has built-in namespace for handling email settings, which is System.Net.Mail namespace. In the following example, I’ll use two classes from the System.Net.Mail namespace:

  • For email settings, we will use the MailMessage class and
  • For smtp settings and sending email, we will use the SmtpClient class

I guess you all know how to send mails via SMTP server, if not then please follow my first tutorial about how to send test mail using gmail smtp settings here.

Asp .Net Gridview Data

HTML Markup – [.aspx]

Following is the complete HTML markup code for your .aspx page:

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
<title>Send asp .net Gridview Data in mail in c#, vb.net</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table>
<tr>
<td colspan=”2″>
<h4>Send asp.net gridview result in mail in c#, vb.net</h4>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID=”txtToEmail” runat=”server” Width=”215″ Height=”25″
placeholder=”To email: example@example.com”></asp:TextBox>
<asp:RequiredFieldValidator ID=”rfvToEmail” runat=”server” ErrorMessage=”Required”
ControlToValidate=”txtToEmail” ForeColor=”Red” Display=”Dynamic”>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID=”revToEmail” runat=”server” ForeColor=”Red”
ValidationExpression=”\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”
ControlToValidate=”txtToEmail” ErrorMessage=”Invalid Email”>
</asp:RegularExpressionValidator>
</td>
<td>
<asp:Button ID=”btnSend” runat=”server” Text=”Send Result!” OnClick=”btnSend_Click” />
</td>
</tr>
<tr><td colspan=”2″>&nbsp;&nbsp;</td>
</tr>
<tr>
<td colspan=”2″>
<asp:GridView ID=”grdResultDetails” runat=”server” AutoGenerateColumns=”false”>
<HeaderStyle Font-Bold=”true” BackColor=”#ff6600″ BorderColor=”#222″
ForeColor=”White” Height=”30″ />
<Columns>
<asp:BoundField DataField=”Subjects” HeaderText=”Subjects” ItemStyle-Width=”200″
ItemStyle-HorizontalAlign=”Center” />
<asp:BoundField DataField=”Marks” HeaderText=”Marks” ItemStyle-Width=”200″
ItemStyle-HorizontalAlign=”Center” />
<asp:BoundField DataField=”Grade” HeaderText=”Grade” ItemStyle-Width=”200″
ItemStyle-HorizontalAlign=”Center” />
</Columns>
</asp:GridView>
</td>
</tr>
<tr><td colspan=”2″>&nbsp;&nbsp;</td>
</tr>
<tr>
<td colspan=”2″>
<asp:Label ID=”lblMsg” runat=”server”></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Note: If you want to send gridview selected rows in mail, check out my previous tutorial on how to export gridview selected rows to word excel text pdf or send in mail here.

Function To Send Asp .net Gridview Data in Mail – [C#]

Following is the namespace required for sending emails:

using System.Net.Mail;
using System.Text;
using System.IO;

Following is the code that we need to use for sending emails:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGridData();
}
}private void LoadGridData()
{
System.Data.DataTable dtSubData = new System.Data.DataTable();

//Creating grid columns
dtSubData.Columns.Add(“Subjects”);
dtSubData.Columns.Add(“Marks”);
dtSubData.Columns.Add(“Grade”);

//Adding row deails
dtSubData.Rows.Add(“Asp.net”, “70”, “B+”);
dtSubData.Rows.Add(“C#”, “80”, “A”);
dtSubData.Rows.Add(“Vb.net”, “76”, “A”);
dtSubData.Rows.Add(“HTML”, “91”, “A+”);
dtSubData.Rows.Add(“CSS”, “95”, “A+”);
dtSubData.Rows.Add(“JavaScript”, “78”, “A”);
dtSubData.Rows.Add(“jQuery”, “74”, “A”);

//Binding details to gridview
grdResultDetails.DataSource = dtSubData;
grdResultDetails.DataBind();
}

private string GridViewToHtml(GridView grdResultDetails)
{
StringBuilder objStringBuilder = new StringBuilder();
StringWriter objStringWriter = new StringWriter(objStringBuilder);
HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
grdResultDetails.RenderControl(objHtmlTextWriter);
return objStringBuilder.ToString();
}

public override void VerifyRenderingInServerForm(Control control)
{
//Required to verify that the control is rendered properly on page
}

protected void btnSend_Click(object sender, EventArgs e)
{
try
{
string Subject = “This is test mail with gridview data”,
Body = GridViewToHtml(grdResultDetails),
ToEmail = txtToEmail.Text.Trim();

string SMTPUser = “yourname@gmail.com”, SMTPPassword = “yourpassword”;

MailMessage mail = new MailMessage();
mail.From = new MailAddress(SMTPUser, “AspnetO”);
mail.To.Add(ToEmail);
mail.Subject = Subject;
mail.Body = Body;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.Normal;

SmtpClient smtp = new SmtpClient();
//if you are using your smtp server, then change your host like “smtp.yourdomain.com”
smtp.Host = “smtp.gmail.com”;
//chnage your port for your host
smtp.Port = 25; //or you can also use port# 587
smtp.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPassword);
//if you are using secure authentication using SSL/TLS then “true” else “false”
smtp.EnableSsl = true;

smtp.Send(mail);

lblMsg.Text = “Success: Mail sent successfully!”;
lblMsg.ForeColor = System.Drawing.Color.Green;
}
catch (SmtpException ex)
{
//catched smtp exception
lblMsg.Text = “SMTP Exception: “ + ex.Message.ToString();
lblMsg.ForeColor = System.Drawing.Color.Red;
}
catch (Exception ex)
{
lblMsg.Text = “Error: “ + ex.Message.ToString();
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}

Function To Send Asp .net Gridview Data in Mail – [Vb.net]

Following is the namespace required for sending emails:

Imports System.Net.Mail;
Imports System.Text;
Imports System.IO;

Following is the code that we need to use for sending emails:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGridData()
End If
End SubPrivate Sub LoadGridData()
Dim dtSubData As New System.Data.DataTable()

‘Creating grid columns
dtSubData.Columns.Add(“Subjects”)
dtSubData.Columns.Add(“Marks”)
dtSubData.Columns.Add(“Grade”)

‘Adding row deails
dtSubData.Rows.Add(“Asp.net”, “70”, “B+”)
dtSubData.Rows.Add(“C#”, “80”, “A”)
dtSubData.Rows.Add(“Vb.net”, “76”, “A”)
dtSubData.Rows.Add(“HTML”, “91”, “A+”)
dtSubData.Rows.Add(“CSS”, “95”, “A+”)
dtSubData.Rows.Add(“JavaScript”, “78”, “A”)
dtSubData.Rows.Add(“jQuery”, “74”, “A”)

‘Binding details to gridview
grdResultDetails.DataSource = dtSubData
grdResultDetails.DataBind()
End Sub

Private Function GridViewToHtml(ByVal grdResultDetails As GridView) As String
Dim objStringBuilder As New StringBuilder()
Dim objStringWriter As New StringWriter(objStringBuilder)
Dim objHtmlTextWriter As New HtmlTextWriter(objStringWriter)
grdResultDetails.RenderControl(objHtmlTextWriter)
Return objStringBuilder.ToString()
End Function

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
‘Required to verify that the control is rendered properly on page
End Sub

Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim Subject As String = “This is test mail with gridview data”,
Body As String = GridViewToHtml(grdResultDetails),
ToEmail As String = txtToEmail.Text.Trim()

Dim SMTPUser As String = “yourname@gmail.com”,
SMTPPassword As String = “yourpassword”

Dim mail As New MailMessage()
mail.From = New MailAddress(SMTPUser, “AspnetO”)
mail.To.Add(ToEmail)
mail.Subject = Subject
mail.Body = Body
mail.IsBodyHtml = True
mail.Priority = MailPriority.Normal

Dim smtp As New SmtpClient()
‘if you are using your smtp server, then change your host like “smtp.yourdomain.com”
smtp.Host = “smtp.gmail.com”
‘chnage your port for your host
smtp.Port = 25 ‘or you can also use port# 587
smtp.Credentials = New System.Net.NetworkCredential(SMTPUser, SMTPPassword)
‘if you are using secure authentication using SSL/TLS then “true” else “false”
smtp.EnableSsl = True

smtp.Send(mail)

lblMsg.Text = “Success: Mail sent successfully!”
lblMsg.ForeColor = System.Drawing.Color.Green
Catch ex As SmtpException
‘catched smtp exception
lblMsg.Text = “SMTP Exception: “ & ex.Message.ToString()
lblMsg.ForeColor = System.Drawing.Color.Red
Catch ex As Exception
lblMsg.Text = “Error: “ & ex.Message.ToString()
lblMsg.ForeColor = System.Drawing.Color.Red
End Try
End Sub

During Development, I Faced Following Error:

Control ‘grdResultDetails’ of type ‘GridView’ must be placed inside a form tag with runat=server

Server Error in ‘/’ Application.


Control ‘grdResultDetails’ of type ‘GridView’ must be placed inside a form tag with
runat=server.

Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Control ‘grdResultDetails’ of type ‘GridView’ must be
placed inside a form tag with runat=server.

To resolve this issue, please check how to solve control ‘grdResultDetails’ of type ‘GridView’ must be placed inside a form tag with runat=server.

RegisterForEventValidation can only be called during Render();

Server Error in ‘/’ Application.


RegisterForEventValidation can only be called during Render();

Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: RegisterForEventValidation can only be
called during Render();

To resolve this issue, please check how to solve RegisterForEventValidation can only be called during Render();.

Example Result

Asp net gridview Data

Download Example

[wpdm_package id=’5427′]

LEAVE A REPLY

Please enter your comment!
Please enter your name here
Captcha verification failed!
CAPTCHA user score failed. Please contact us!