Tuesday, 8 April 2014

send email using Asp.Net with c#

In this article I'm going to explain how to send email in ASP.NET application using C#.
          ASP.NET allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP). Here I’ll explain Namespace, Classes, Properties and Methods which are all used to send mail from ASP.NET application.

Namespace:  

System.Net.Mail
The System.Net.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery.

Classes:

 SmtpClient()
Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).MailMessage()
MailMessage()
Represents an e-mail message that can be sent using the SmtpClient class.

Properties

Gets or sets the credentials used to authenticate the sender.
EnableSsl:
Specify whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection. 
Gets or sets the name or IP address of the host used for SMTP transactions.
Port :
Gets or sets the port used for SMTP transactions.
UseDefaultCredentials:
Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.
Gets or sets a value that specifies the amount of time after which a synchronous Send call times out.

 Method:

Dispose():
Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of theSmtpClient class.
Note
Always call Dispose before you release your last reference to the SmtpClient. Otherwise, the resources it is using will not be freed so the garbage collector can reclaim the memory.

Send(MailMessage):
Sends the specified message to an SMTP server for delivery.

Designer Source Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <table width="600px" align="center">
        <tr>
            <td colspan="2" align="center"><b>Send Mail</b></td>
        </tr>
        <tr>
        <td colspan="2"></td>
        </tr>          
        <tr>
            <td> To </td>
            <td> <asp:TextBox ID="txtToMail" runat="server"></asp:TextBox> </td>
        </tr>
        <tr>
            <td> Subject </td>
            <td> <asp:TextBox ID="txtSubject" runat="server" Width="400">
            </asp:TextBox> </td>
        </tr>
        <tr>
            <td> Message </td>
            <td> <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"
                                Width="400px" Height="200px"></asp:TextBox></td>
        </tr>
        <tr>
            <td> &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td colspan="2" align="center"> <asp:Button ID="btnSubmit" runat="server"
                                   OnClick="btnSubmit_Click" Text="Send" /> </td>
        </tr>
        <tr>
        <td colspan="2"><asp:Label ID="lblMsg" runat="server" ></asp:Label> </td>
        </tr>                 
    </table>
    </div>
    </form>
</body>
</html> 

Code Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        MailMessage Msg = new MailMessage();
        Msg.From = new MailAddress("example@gmail.com");
        Msg.To.Add(txtToMail.Text);
        Msg.Subject = txtSubject.Text;
        Msg.Body = txtMessage.Text;
        Msg.IsBodyHtml = true;

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
        NetworkCred.UserName = "example@gmail.com";
        NetworkCred.Password = "Your password";
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.EnableSsl = true;
        smtp.Send(Msg);
        lblMsg.Text = "Email has been successfully sent..!!";
    }
}




Form Authentication in Asp.net

There are times when you want to validate users hitting a web site on your own rather than using Windows or Passport authentication. That requires forms based security. This article shows you how to implement Forms Based Authentication.
Hitting any web page on the site will automatically redirect to the login form. When the login form has authenticated the user, it will automatically redirect back to the originally requested page. Failure to log in will prohibit the user from hitting the originally requested page.
Each example below is shown in C#. Use the appropriate code for the language you are using.
In the web.config file in the root of the web site, insert this XML:
<authentication mode="Forms"> <forms name="login" loginUrl="login.aspx" /></authentication> <authorization> <allow roles="bigboss" /> <allow roles="wimpyuser" /> <allow users="admin" /> <deny users="*" /></authorization>
Change the rules to give permissions to the proper users and roles. You may create a different web.config and its authorization section in each subdirectory with different rules.
In the global.asax file, insert this code:
c#]
using System.Security.Principal;
using System.Web.Security;
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
//Fires upon attempting to authenticate the use 
if (!(HttpContext.Current.User == null))
{  
if (HttpContext.Current.User.Identity.IsAuthenticated)
{  
if (HttpContext.Current.User.Identity.GetType() == typeof(FormsIdentity))  
{  
FormsIdentity fi = (FormsIdentity) HttpContext.Current.User.Identity;  
FormsAuthenticationTicket fat = fi.Ticket;  
String[] astrRoles = fat.UserData.Split('|'); 
HttpContext.Current.User = new GenericPrincipal(fi, astrRoles); } 
}
}
}
Create a Web Form named login.aspx, set the style to Flow Layout, and put this onto the page:
<table height="66%" width="100%">
<tr>
<td align="middle">
<table id="loginbox" width="300" class="itemstyle">
<tr>
<td id="login" align="middle" colspan="3">Login</td>
</tr>
<tr>
<td>Username:</td>
<td><asp:textbox id="txtUsername" tabindex="4" runat="server"
columns="12"></asp:textbox></td>
<td valign="center" align="middle" rowspan="2">
<asp:button id="btnLogin" runat="server" text="Login"
cssclass="button"></asp:button></td>
<tr>
<td>Password:</td>
<td><asp:textbox id="txtPassword" runat="server" columns="12"
textmode="Password"></asp:textbox></td>
</tr>
<tr>
<td>&nbsp;</td>
<td colspan="2"><asp:label id="lblError" runat="server"
forecolor="Red" visible="False">Not a valid username or password.</asp:label>
</td>
</tr>
</table>
</td>
</tr>
</table>

In the CodeBehind for login.aspx, put this code:

[c#]
using System.Web.Security; private void btnLogin_Click(object sender, System.EventArgs e) { if (ValidateUser(txtUsername.Text, txtPassword.Text)) { FormsAuthentication.Initialize(); String strRole = AssignRoles(txtUsername.Text); //The AddMinutes determines how long the user will be logged in after leaving //the site if he doesn't log off. FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, strRole, FormsAuthentication.FormsCookiePath); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat))); Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false)); } else lblError.Visible = true; } private Boolean ValidateUser(String strUsername, String strPassword) { //Return true if the username and password is valid, false if it isn't return ((strUsername == "admin") && (strPassword == "password")); } private String AssignRoles(String strUsername) { //Return a | separated list of roles this user is a member of if (txtUsername.Text == "admin") return "bigboss|wimpyuser"; else return String.Empty; }
Change the ValidateUser and AssignRoles to do lookups into a database or other data store instead of the hardcoded validation and role assignment shown.
On each page on the site, you will need a way to log out. Simply put a hyperlink to the logout page:
<asp:HyperLink id="hlLogout" runat="server"
NavigateUrl="logout.aspx">Logout</asp:HyperLink>

The logout.aspx page should have this on it:
<table width="100%">
<tr>
<td align="middle">
You have been logged out.
<asp:hyperlink id="hlLogin" runat="server"
navigateurl="default.aspx">Log back in.</asp:hyperlink>
</td>
</tr>
</table>

The CodeBehind for the logout page should include this:
[c#]
using System.Web.Security; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Session.Abandon(); FormsAuthentication.SignOut(); }
You can put things that are only allowable to certain roles on your web page by using code like this:
[c#]
hlAdmin.Visible = Page.User.IsInRole("bigboss");