July 12, 2011 06:41 by
Scott
This brief article demonstrates the simplest way and step by step instructions on how to send email from aspx page using a gmail account. After reading this you'll be able to send HTML formatted email messages by using Asp.Net and C#.
In order to send an email from gmail account programmatically, you have to include the following namespace:
using System.Net.Mail; // contains classes for SMTP settings, email sending etc
Let's take a look at the soure of aspx page. It has only three fields and a button to send email
<form id="form1" runat="server">
<asp:Label ID="lblEmailAddress" runat="server" Text="Email Address:"></asp:Label>
<asp:TextBox ID="txtEmailAddress" runat="server" Width="300px"></asp:TextBox>
<br />
<asp:Label ID="lblEmailSubject" runat="server" Text="Subject of Email:"></asp:Label>
<asp:TextBox ID="txtEmailSubject" runat="server" Width="300px"></asp:TextBox>
<br />
<asp:Label ID="lblEmailMessageBody" runat="server" Text="Email Message Body:"></asp:Label>
<asp:TextBox ID="txtEmailMessageBody" runat="server" Rows="5" TextMode="MultiLine"
Width="300px"></asp:TextBox>
<br />
<asp:Button ID="btnSendEmail" runat="server" OnClick="btnSendEmail_Click" Text="Send Email" />
<asp:Label ID="lblEmailStatus" runat="server"></asp:Label>
</form>
Email Address: the address to which the email is to be sent
Subject of Email: The subject line of email and
Email Message Body: As we want to send HTML instead of simple plain text so whatever is placed in this field, will be formatted using html styles.
Pretty simple ... ok let's move to server side code:
protected void btnSendEmail_Click(object sender, EventArgs e)
{
lblEmailStatus.Text = "";
if (SendEmails())
lblEmailStatus.Text = "Your Email has been sent";
else
lblEmailStatus.Text = "Error: Sending Email";
}
This is the event handler of Send Email button. It simply calls SendEmails() function and sets the status of label whether the email is sent successfully or not. Now lets look at SendEmail function:
private bool SendEmails()
{
try
{
MailMessage mail = new MailMessage();
mail.To.Add(txtEmailAddress.Text);
mail.From = new MailAddress("[email protected]");
mail.Subject = "Sending Email from aspx: " + this.txtEmailSubject.Text;
string Body = "<div style='font-family:Comic Sans MS; color:Navy; font-size:small'>" +
"<br/>" +
"<b>Email Date and Time:</b> " + DateTime.Now.ToString() + "" +
"<br/>" +
"<br/>" +
"See the Following Email Message:" +
"<br/>" +
"<br/>" +
"<b>" + this.txtEmailMessageBody.Text + "</b>" +
"<br/>" +
"<hr/>" +
"</div>";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "email password");
smtp.EnableSsl = true;
smtp.Send(mail);
return true;
}
catch (Exception)
{
return false;
}
}
First we will build the actual email message i.e. MailMessage, then configure the SmtpClient and send the email using that SmtpClient. One important thing: Gmail is using 587 of the host smtp.gmail.com
Rest the code is pretty simple and neat ... let me know if you have any questions regarding Sending email.
Another same tutorial, How to Send Email Using Gmail in ASP.NET
July 6, 2011 07:45 by
Scott
In this article I am explaining how to upload multiple files by dynamically adding FileUpload controls using JavaScript.
Here I will explain how one can create a multiple file uploading controls in a very simple manner and very less amount of code. With this example one will able to perform the following functions
1. Add FileUpload Controls dynamically using JavaScript
2. Remove FileUpload Controls dynamically using JavaScript.
Since I am using JavaScript the UI becomes elegant since no need of postback or AJAX to add or remove FileUpload Controls.
Adding and Removing FileUpload Controls using JavaScript
Below is the HTML markup of the page. As you can see I have added a HTML button in order to add new FileUpload Controls, a DIV FileUploadContainer in which the dynamic FileUpload Controls will be added and a ASP.Net Upload Button in order to upload the files when the Upload Button us clicked.
An important think to note that you will need to add enctype="multipart/form-data to the form in order to allow the uploading of files through dynamic FileUpload controls.
<form id="form1" runat="server" enctype="multipart/form-data" method = "post">
<span style ="font-family:Arial">Click to add files</span>
<input id="Button1" type="button" value="add" onclick = "AddFileUpload()" />
<br /><br />
<div id = "FileUploadContainer">
<!--FileUpload Controls will be added here -->
</div>
<br />
<asp:Button ID="btnUpload" runat="server"
Text="Upload" OnClick="btnUpload_Click" />
</form>
Now in order to add and remove the FileUpload Controls dynamically here is the JavaScript functions that are used.
<script type = "text/javascript">
var counter = 0;
function AddFileUpload()
{
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
function RemoveFileUpload(div)
{
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
</script>
As you will notice above first I am creating a DIV element and then adding a HTML FileUpload Control along with a HTML Button in order to remove the FileUpload Controls. Also onclick of the Remove button I am calling the RemoveFileUpload function which removes the dynamically created FileUpload control.
Server Side Uploading of Files
Server Side I have written the following code in the Click event of the Upload Button
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
if (PostedFile.ContentLength > 0)
{
string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
PostedFile.SaveAs(Server.MapPath("Files\\") + FileName);
}
}
}
VB.Net
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs)
For i As Integer = 0 To Request.Files.Count – 1
Dim PostedFile As HttpPostedFile = Request.Files(i)
If PostedFile.ContentLength > 0 Then
Dim FileName As String = System.IO.Path.GetFileName(PostedFile.FileName)
PostedFile.SaveAs(Server.MapPath("Files\") + FileName)
End If
Next
End Sub
In the above code snippet I am simply looping through the Request.Files Collection which contains the uploaded Files and then I am saving each of them one by one in a Folder called Files within my website root folder.
Web.Config Configurations
Since this article deals with uploading multiple files it is important to discuss the maximum file size allowed. By default ASP.Net allows files of size maximum 4MB at a time. Hence in order to upload more data we will need to increase this limit. Refer the httpRuntime section of the Web.Config, if it is not present in your Web.Config you can simply paste the one given below in your file.
<httpRuntime
executionTimeout="110"
maxRequestLength="4096"
requestLengthDiskThreshold="80"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="5000"
enableKernelOutputCache="true"
enableVersionHeader="true"
requireRootedSaveAsPath="true"
enable="true"
shutdownTimeout="90"
delayNotificationTimeout="5"
waitChangeNotification="0"
maxWaitChangeNotification="0"
enableHeaderChecking="true"
sendCacheControlHeader="true"
apartmentThreading="false"
/>
In order to increase the maximum file size limit you will need to change the value of the maxRequestLength attribute in kilobytes (KB). For example if you want to set the upload limit to 10 MB you will have to set the value to 10240. Another important parameter is executionTimeout. It determines the maximum amount of time in seconds ASP.Net will process the request and after which it will stop the processing. By default the value is 110 seconds. You can modify it to the value that suits your needs
The above code has been tested in the following browsers
June 30, 2011 06:42 by
Scott
A typical web.config file in v2.0 could have the following section which is placed directly under the root <configuration> section.
<connectionStrings>
<remove name="LocalSqlServer" />
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
<add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
connectionStrings>
<remove name="LocalSqlServer" />
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
<add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
You can reference this directly from code using:
[C#]
string connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
[VB]
Dim connStr As String = ConfigurationManager.ConnectionStrings("MainConnStr").ConnectionString
Note that the namespace for this is System.Configuration so for a console application the full namespace is required.
Or you can reference this declaratively within the ConnectionString property of a SqlDataSource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MainConnStr %>"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]" />
June 16, 2011 06:55 by
Scott
If you want to send email using your Gmail account or using Gmail's smtp server in ASP.NET application or if you don't have a working smtp server to send mails using your ASP.NET application or aspx page than sending e-mail using Gmail is best option.
You need to write code like this
First of all add below mentioned namespace in code behind of aspx page from which you want to send the mail.
using System.Net.Mail;
Now write this code in click event of button
C# code
protected void Button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To.Add("[email protected]");
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Email using Gmail";
string Body = "Hi, this mail is to test sending mail"+
"using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("[email protected]","YourGmailPassword");
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);
}
VB.NET code
Imports System.Net.Mail
Protected Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
Dim mail As MailMessage = New MailMessage()
mail.To.Add("[email protected]")
mail.To.Add("[email protected]")
mail.From = New MailAddress("[email protected]")
mail.Subject = "Email using Gmail"
String Body = "Hi, this mail is to test sending mail"+
"using Gmail in ASP.NET"
mail.Body = Body
mail.IsBodyHtml = True
Dim smtp As SmtpClient = New SmtpClient()
smtp.Host = "smtp.gmail.com" //Or Your SMTP Server Address
smtp.Credentials = New System.Net.NetworkCredential
("[email protected]","YourGmailPassword")
smtp.EnableSsl = True
smtp.Send(mail)
End Sub
You also need to enable POP by going to settings > Forwarding and POP in your gmail account
Change [email protected] to your gmail ID and YourGmailPassword to Your password for Gmail account and test the code.
If your are getting error mentioned below
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."
than you need to check your Gmail username and password.
If you are behind proxy Server then you need to write below mentioned code in your web.config file
<system.net>
<defaultProxy>
<proxy proxyaddress="YourProxyIpAddress"/>
</defaultProxy>
</system.net>
If you are still having problems them try changing port number to 587
smtp.Host = "smtp.gmail.com,587";
If you still having problems then try changing code as mentioned below
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = False;
smtp.Credentials = new System.Net.NetworkCredential
("[email protected]","YourGmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);
Hope this help!!
June 2, 2011 05:27 by
Scott
Introduction
When Microsoft released its flavour of AJAX framework named "ASP.NET AJAX" as part of ASP.NET 3.0 preview, it did not have much competency when compared to other AJAX frameworks. But when I evaluated ASP.NET AJAX 4.0, I was really inspired with the new features that are completely focused on your browser technologies such as XHTML and JavaScript. I really admired the effort made by the ASP.NET AJAX team. There could not be any second opinion when you see the following features:
- Template based client side programming
- DataView and DataContext
- Live Data Binding
Template Programming
Template provides pattern to design a web UI form and enables to put placeholders for runtime data. For example, I've designed a web page to display AdventureWorks database Product data through ADO.NET data service. The entity model (edmx) is:
The service code is:
public class AWProductDataService : DataService
{
public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
}
}
By ASP.NET templates, the page looks like:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="ClientTemplateAndDataViewDemo.aspx.cs"
Inherits="CoreEnhancements.AJAX.ClientTemplateAndDataViewDemo" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Microsoft Tech.Ed - Client-side Templating Demo</title>
<style type="text/css">
.sys-template {display:none}
</style>
<script type="text/javascript" src="../scripts/MicrosoftAjax.debug.js"></script>
<script type="text/javascript" src="../scripts/MicrosoftAjaxTemplates.debug.js">
</script>
<script type="text/javascript" src="../scripts/MicrosoftAjaxAdoNet.debug.js">
</script>
<script type="text/javascript">
var dataContext = new Sys.Data.AdoNetDataContext();
dataContext.set_serviceUri("AWProductDataService.svc");
dataContext.initialize();
</script>
</head>
<body xmlns:sys="javascript:Sys" xmlns:dataview="javascript:Sys.UI.DataView"
sys:activate="*">
<form id="form1" runat="server">
<div>
<table border="1">
<thead>
<tr>
<td>Name</td>
<td>List Price</td>
<td>Size</td>
<td>Weight</td>
</tr>
</thead>
<tbody class="sys-template" sys:attach="dataview" dataview:autofetch="true"
dataview:dataprovider="{{ dataContext }}"
dataview:fetchoperation="Products">
<tr>
<td>{binding Name }</td>
<td>{binding ListPrice}</td>
<td>{binding Size}</td>
<td>{binding Weight}</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
I have used a typical HTML table for displaying the data. You can see some new attributes in <TBODY> and data place holders in <TD>. ASP.NET AJAX 4.0 has a dedicated template engine to parse these new attributes and data place holders. ASP.NET AJAX has defined a rich set of attributes and data placeholder patterns collectively called as expression language which are none other than X(HT)ML and JavaScript. Remarkable point here is its XHTML compliance, so these are not custom attributes in the regular HTML elements. The class attribute of the <TBODY> is set to sys-template, which is a convention used to hide the initial template from the user. .sys-template {display:none} The fields or properties of a data item which are needed to be rendered on data place holders can be expressed by {{ }} or { }.
DataContext
Template requires data for its place holders as contexts. The data context enables to bind any JavaScript array or objects to template. The real power of data context is to interact with JSON/ATOM based web services. ASP.NET AJAX provides two data contexts in MicrosoftAjaxAdoNet.js:
- Sys.Data.DataContext
- Sys.Data.AdoNetDataContext
The data context tracks all changes to the data automatically using new Sys.Observer object. AdoNetDataContext supports additional features for ADO.NET data services such as identity management, links and association between entity sets. The below code sample describes how to interact with AdventureWorks Product's ADO.NET data service:
var dataContext = new Sys.Data.AdoNetDataContext();
dataContext.set_serviceUri("AWProductDataService.svc");
dataContext.initialize();
The set_serviceUri() method is used to interact with WCF AJAX or ADO.NET data service. The initialize() method does initialization or invocation.
Data View
This is the fundamental component for templates to display data defined in System.UI.DataView. This is similar to server side data source component supports to bind any JavaScript object or array or to any ASP.NET AJAX component. It has two properties to bind a data set:
- data - To bind a JavaScript array or object
- dataprovider - To bind to a WCF service
The fetchoperation property is used to set which method needs to be invoked for fetching data. In the code snippet 1, I've set the dataContext declared in code snippet 2 as data source. To run this application, refer to the following ASP.NET AJAX client side libraries:
- MicrosoftAjax.js
- MicrosoftAjaxTemplates
- MicrosoftAjaxAdoNet
The xmlns:sys declares the namespace Sys for the entire page (Code 1. Line 2). The xmlns:dataview declares DataView control. A data view instance has been associated with <TBODY> using sys:attach.
The following figure shows the conceptual model of the template programming:
The output code is: