Sunday, September 13, 2009

Send Mail in ASP.net 2.0 using SMTP Client and Mail Message with GMail

Send Mail Using SMTPClient and MailMessage in ASP

Send Mail Using SMTPClient and MailMessage in ASP.net 2.0 with GMail


Introduction

Sending Mail is become essential to web development and many sites. They used to send the reminders, the promotions to the subscribers and so forth. Email serves as the asynchronous notification and information distribution system.

Fortunately, ASP.net makes sending email very ease and powerful. Now the developer can utilize and develop powerful mailing system with very few lines of code. The .Net Framework provides the very rich sets of object which is used to send mail. System.Net.Mail namespace has all the class (objects) which one can use to send mails.


Exploring the Classes in the System.Net.Mail Namespace

There are 16 different classes in the System.Net.Mail namespace, all related to send email to a specified Simple Mail Transfer Protocol (SMTP) server for delivery. The two core classes in this namespace are:

  • MailMessage - represents an email message; has properties like From, To, Subject, Body, and so on.
  • SmtpClient - sends a specified Mail Message instance to a specified SMTP server.


Numbers of Steps performed to send mail using ASP.net 2.0 are

  1. Create the MailMessage Object with all the information has mentioned above
  2. Create the SmtpClient Object to send the Message created using the MailMessage Object.
  3. Specify the SMTP Host (server) name and its port to send mail from the specified mail id.
  4. You can use the GMail Smtp server to send mail if you don’t have one.
  5. You can send the attachment with the mails which you can specified to Mail Message properties.


Configure SMTP Server Configuration in Web.Config File


Add below code in config file and replace the properties with actual values

Configuration >
  
  system.net>
    mailSettings>
      
        
             host="serverName" 
             port="portNumber"
             userName="username"
             password="password" />
      
    
  
 
  
    ...
  


You can configure the SMTP properties in code behind too depends how you want to use.

Send Mail from Mailing Page

Default.aspx

<table bordercolor="#339933" cellspacing="0" cellpadding="4" width="55%" align="center" border="1">
<tr>
<td>
<table cellpadding="4" width="70%" align="center" border="0"> <tr bgcolor="#339933"> 
    <td align="center" colspan="2" style="background-color: #999999"><span id="lblHeader" style="font-weight:bold;">Gmail Account Details for Sending Mailsspan>td> tr>
<tr>
<td valign="middle" align="right" width="40%">Username:td> <td
valign="middle" width="60%"> <input name="txtUserName" type="text" id="txtUserName" style="font-family:Verdana;font-size:X-Small;width:350px;" />
td>
tr>
<tr>
<td valign="middle" align="right" width="40%">Passwordtd> <td
valign="middle" width="60%"> <input name="txtPassword" type="password" id="txtPassword" style="font-family:Verdana;font-size:X-Small;width:350px;" />
td>
tr>
<tr bgcolor="#339933"> <td align="center" colspan="2" 
        style="background-color: #999999"><span id="Label1" style="font-weight:bold;">SMTP
Mail with Attachmentspan>td>
tr>
<tr>
<td valign="middle" align="right" width="40%">From :td> <td valign="middle"
width="60%"><input name="txtSender" type="text" id="txtSender" tabindex="1" style="font-family:Verdana;font-size:X-Small;width:350px;" />td>
tr>
<tr>
<td valign="middle" align="right">To :td>
<td><input name="txtReceiver" type="text" id="txtReceiver" tabindex="1" style="font-family:Verdana;font-size:X-Small;width:350px;" />td>
tr>
<tr>
<td valign="middle" align="right">Cc :td>
<td><input name="txtCc" type="text" id="txtCc" tabindex="1" style="font-family:Verdana;font-size:X-Small;width:350px;" />td>
tr>
<tr>
<td valign="middle" align="right">Bcc :td>
<td><input name="txtBcc" type="text" id="txtBcc" tabindex="1" style="font-family:Verdana;font-size:X-Small;width:350px;" />td>
tr> <tr>
<td valign="middle" align="right">Subject :td>
<td><input name="txtSubject" type="text" id="txtSubject" tabindex="2" style="font-family:Verdana;font-size:X-Small;width:350px;" />td>
tr>
<tr>
<td valign="middle" align="right">Format :td>
<td><table id="rblMailFormat" border="0">
        <tr>
               <td><input id="rblMailFormat_0" type="radio" name="rblMailFormat" value="Text" checked="checked" tabindex="3" /><label for="rblMailFormat_0">Textlabel>td><td><input id="rblMailFormat_1" type="radio" name="rblMailFormat" value="HTML" tabindex="3" /><label for="rblMailFormat_1">HTMLlabel>td>
        tr>
table>td>
tr>
<tr>
<td valign="middle" align="right">Message :td>
<td height="84"> <p><textarea name="txtBody" rows="5" cols="40" id="txtBody" tabindex="4" style="font-family:Verdana;font-size:X-Small;width:350px;">textarea>p> td>
tr>
<tr>
<td valign="middle" align="right">Attachment :td><td><input name="inpAttachment1" type="file" id="inpAttachment1" tabindex="5" size="53" />td> tr>
<tr>
<td align="center" colspan="2"><input type="submit" name="btnSend" value="Send" id="btnSend" tabindex="9" style="width:100px;" />td>
tr>
<tr>
<td align="center" colspan="2"><span id="lblMessage">span>
td>
tr>
table>
td> tr> table>
    form>








Code behind Default.aspx.cs

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;

using System.IO;

using System.Drawing;

………………………….

protected void btnSend_Click(object sender, EventArgs e)

{

try

{

/* Create a new blank MailMessage with the from and to

adreesses*/

MailMessage mailMessage = new MailMessage(txtSender.Text, txtReceiver.Text);

/*Checking the condition that the cc is empty or not if

not then * include them

*/

if (txtCc.Text != null && txtCc.Text != string.Empty)

{

mailMessage.CC.Add(txtCc.Text);

}

/*Checking the condition that the Bcc is empty or not

if not then

* include them

*/

if (txtBcc.Text != null && txtBcc.Text != string.Empty)

{

mailMessage.Bcc.Add(txtBcc.Text);

}

//Ading Subject to the Mail

mailMessage.Subject = txtSubject.Text;

//Adding the Mail Body

mailMessage.Body = txtBody.Text;

/* Set the properties of the MailMessage to the

values on the form as per the mail is HTML formatted or plain text */

if (rblMailFormat.SelectedItem.Text ==

"Text")

mailMessage.IsBodyHtml = false;

else

mailMessage.IsBodyHtml = true;

/* We use the following variables to keep track of

attachments and after we can delete them */

string attach1 = null;

string attach2 = null;

string attach3 = null;

/*strFileName has a attachment file name for

attachment process. */

string strFileName = null;

/* Bigining of Attachment1 process & Check the first open file dialog for a attachment */

if (inpAttachment1.PostedFile != null)

{

/* Get a reference to PostedFile object */

HttpPostedFile attFile = inpAttachment1.PostedFile;

/* Get size of the file */

int attachFileLength = attFile.ContentLength;

/* Make sure the size of the file is > 0 */

if (attachFileLength > 0)

{

/* Get the file name */

strFileName = Path.GetFileName(inpAttachment1.PostedFile.FileName);

/* Save the file on the server */

inpAttachment1.PostedFile.SaveAs(Server.MapPath(strFileName));

/* Create the email attachment with the uploaded file

*/

Attachment attach = new

Attachment(Server.MapPath(strFileName));

/* Attach the newly created email attachment */

mailMessage.Attachments.Add(attach);

/* Store the attach filename so we can delete it later

*/

attach1 = strFileName;

}

}

/* Set the SMTP server and send the email with attachment */

SmtpClient smtpClient = new SmtpClient();

smtpClient.Host = "smtp.gmail.com";

smtpClient.Port = 465;

smtpClient.Credentials = new System.Net.NetworkCredential(txtUserName.Text, txtPassword.Text);

//this will be the true in case of gamil and it varies

//from the service provider

smtpClient.EnableSsl = true;

smtpClient.Send(mailMessage);

/* Delete the attachements if any */

try

{

if (attach1 != null)

File.Delete(Server.MapPath(attach1));

}

catch { }

/* clear the controls */

txtSender.Text = string.Empty;

txtReceiver.Text = string.Empty;

txtCc.Text = string.Empty;

txtBcc.Text = string.Empty;

txtSubject.Text = string.Empty;

txtBody.Text = string.Empty;

txtUserName.Text = string.Empty;

/* Dispaly a confirmation message to the user. */

lblMessage.Visible = true;

lblMessage.ForeColor = Color.Black;

lblMessage.Text = "Message sent.";

}

catch (Exception ex)

{

/* Print a message informing the user about the exception that was risen */

lblMessage.Visible = true;

lblMessage.ForeColor = Color.Red;

lblMessage.Text = ex.ToString();

}

}


Happy Coding

Saturday, August 29, 2009

Working with IIS Metabase with DirectoryServices in .Net

Introduction:

While working with the IIS we all like to know the settings done on the Virtual Directory are correct or not. So we are going to see how to do that programmatically.

To check some properties of the IIS (Virtual Directory) of Web based application

after install, one can create custom application for that.

There are list of IIS Properties which we can get after post installation. The list of properties exposed by the IIS API or Web Settings Property is mentioned below

  • AuthFlags
  • Path
  • AppFriendlyName
  • EnableDirBrowsing
  • AccessRead
  • AccessExecute
  • AccessWrite
  • AccessScript
  • AuthNTLM
  • EnableDefaultDoc
  • DefaultDoc
  • AspEnableParentPaths

The above settings are configured in the Metabase of the IIS.

IIS Metabase:

IIS Metabase is a structure where IIS configuration settings are stored. The metabase configuration and schema for IIS 4.0 and IIS 5.0 were stored in a binary file, but from IIS6.0 the configuration and setting is stored in single binary file (MetaBase.bin), with plain text, Extensible Markup Language (XML) formatted files named MetaBase.xml and MBSchema.xml. You can navigate through the IIS Metabase using MetaEdit or Metabase Explorer.

The Metabase is based on a hierarchical design with inheritance. Each object in the metabase has a KeyType. The KeyType property specifies the type of metabase key.

Implementation:

.Net provides the namespace which is used to get the properties of the IIS Virtual Directory. .Net have the "System.DirectoryServices" namespace which exposes the DirectoryEntry Class.

Code:

WebSettings.cs:

public class WebSettings

{

//Authentication Bitmask Values

//Constant Value Description

public const int MD_AUTH_ANONYMOUS = 0x00000001;

//Anonymous authentication available.

public const int MD_AUTH_BASIC = 0x00000002;

//Basic authentication available.

public const int MD_AUTH_NT = 0x00000004;

//Windows authentication schemes available.

string Auth_Type;

public string calc(int AuthValue)

{

if (AuthValue == MD_AUTH_ANONYMOUS)

{

Auth_Type = "ANONYMOUS ACCESS ENABLED";

}

if (AuthValue == MD_AUTH_BASIC)

{

Auth_Type = "BASIC ACCESS ENABLED";

}

if (AuthValue == MD_AUTH_NT)

{

Auth_Type = "INTEGRATED WINDOWS ACCESS ENABLED";

}

if (AuthValue == (MD_AUTH_ANONYMOUS + MD_AUTH_NT))

{

Auth_Type = "INTEGRATED WINDOWS + ANONYMOUS ACCESS ENABLED";

}

if (AuthValue == (MD_AUTH_ANONYMOUS + MD_AUTH_BASIC))

{

Auth_Type="BASIC + ANONYMOUS";

}

if (AuthValue == (MD_AUTH_ANONYMOUS + MD_AUTH_NT))

{

Auth_Type = "INTEGRATED + ANONYMOUS";

}

if (AuthValue == (MD_AUTH_BASIC + MD_AUTH_NT))

{

Auth_Type = "BASIC + INTEGRATED";

}

if (AuthValue == (MD_AUTH_ANONYMOUS + MD_AUTH_BASIC + MD_AUTH_NT))

{

Auth_Type = "ANONYMOUS + BASIC + INTEGRATED";

}

return Auth_Type;

}

Main.cs

string serverName;

string vDir;

serverName = System.Environment.MachineName;

vDir = "DirectoryName";

vdir = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/ROOT/" + vDir);

wbs = new WebSettings();

string[] sComp = new string[12];

sComp[0] = "AuthFlags";

sComp[1] = "Path";

sComp[2] = "AppFriendlyName";

sComp[3] ="EnableDirBrowsing";

sComp[4] ="AccessRead";

sComp[5] ="AccessExecute";

sComp[6] ="AccessWrite";

sComp[7] ="AccessScript";

sComp[8] ="AuthNTLM";

sComp[9] ="EnableDefaultDoc";

sComp[10] ="DefaultDoc";

sComp[11] ="AspEnableParentPaths";

ListViewItem[] listViewItem = new ListViewItem[12];

lstIISProperty.Items.Clear();

for (int i = 0; i <>

{

//lstComponents.MultiColumn = 2;

lstIISProperty.Sorting = SortOrder.Ascending;

if (sComp[i] != null)

{

listViewItem[i] = new ListViewItem(new string[]{ sComp[i], IISPropertyValue(sCompi]), fnExpected_Value(sComp[i])}, -1);

lstIISProperty.Items.Add(listViewItem[i]);

}

}

Authentication Modes in ASP.Net for Security

Introduction:

When you begin a program for a customer using ASP.Net, you should consider about security. Security is one of the most important components of any application. Security is even more important when you are making a web application which is exposed to million of users. Asp.net provides classes and methods that ensure that the application is secure from outside attacks. In this article we will investigate the different types of authentication provided by ASP.Net. In web.config file you can set authentication mode value 'windows' or 'forms'. What's about difference and how to you use them? (Authentication have some other values to, this article does not consider them.)

Configure the Security Settings in the Web.config File:

This section demonstrates how to add and modify the and configuration sections to configure the ASP.NET application to use window-based or forms-based authentication.

How to use mode "Windows"?

Change the authentication mode to Windows.

Windows Authentication mode provides the developer to authenticate a user based on Windows user accounts. This is the default authentication mode provided by ASP.Net. You can easily get the Identity of the user by using User.Identity.Name. This will return the computer name along with the user name. Windows authentication also provides IsInRole method to find the role of the user and than you can give permissions to the user depending on the role.

<authentication mode="Windows">

<forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/" timeout="30" />

authentication>

Deny access to the anonymous user in the section as follows:

<authorization>

<deny users ="?" />

<allow users = "*" />

authorization>

Other you can make a special client to access you project with windows authentication. Code like this (this case you can get value using 'User.Identity.Name', then you can use it to do other work you like.):

<authorization>

<deny users ="?" />

authorization>

How to use mode "Forms"?

Change the authentication mode to Forms.

Insert the tag, and fill the appropriate attributes. (For more information about these attributes, refer to the MSDN documentation)

First you should specify a page and make sure all clients can found it. Code like this

<authentication mode="Forms">

<forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/" timeout="30" />

authentication>

Deny access to the anonymous user in the section as follows:

<authorization>

<deny users ="?" />

authorization>

Second in that page you to validate the user's Id and Password. Code like this:

You can use one of two methods to generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event. Sample code is provided for both scenarios. Use either of them according to your requirement.

(1). Call the RedirectFromLoginPage method to automatically generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event:

private void cmdLogin_ServerClick(object sender, System.EventArgs e)

{

If (ValidateUser(txtUserName.Value,txtUserPass.Value) )

{

FormsAuthentication.RedirectFromLoginPage(txtUserName.Value, false);

}

else

{

Response.Redirect("logon.aspx", true);

}

}

(2). Generate the authentication ticket, encrypt it, create a cookie, add it to the response, and redirect the user. This gives you more control in how you create the cookie. You can also include custom data along with the FormsAuthenticationTicket in this case.

Private void cmdLogin_ServerClick(object sender, System.EventArgs e)

{

if (ValidateUser(txtUserName.Value,txtUserPass.Value) )

{

FormsAuthenticationTicket tkt;

string cookiestr;

HttpCookie ck;

tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,

DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");

cookiestr = FormsAuthentication.Encrypt(tkt);

ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);

if (chkPersistCookie.Checked)

ck.Expires=tkt.Expiration;

ck.Path = FormsAuthentication.FormsCookiePath;

Response.Cookies.Add(ck);

string strRedirect;

strRedirect = Request["ReturnUrl"];

if (strRedirect==null)

strRedirect = "default.aspx";

Response.Redirect(strRedirect, true);

}

else

Response.Redirect("logon.aspx", true);

}

Additional Notes:

You may want to store passwords securely in a database. You can use the FormsAuthentication class utility function named HashPasswordForStoringInConfigFile to encrypt the passwords before you store them in the database or configuration file.

You may want to store the SQL connection information in the configuration file (Web.config) so that you can easily modify it if necessary.

You may consider adding code to prevent hackers who try to use different combinations of passwords from logging on. For example, you can include logic that accepts only two or three logon attempts. If the user cannot log on in a certain number of attempts, you may want to set a flag in the database to not allow that user to log on until that user re-enables his or her account by visiting a different page or by calling your support line. In addition, you should add appropriate error handling wherever necessary.

Because the user is identified based on the authentication cookie, you may want to use Secure Sockets Layer (SSL) on this application so that no one can deceive the authentication cookie and any other valuable information that is being transmitted.

Forms-based authentication requires that your client accept or enable cookies on their browser.

The timeout parameter of the configuration section controls the interval at which the authentication cookie is regenerated. You can choose a value that provides better performance and security.

Certain intermediary proxies and caches on the Internet may cache Web server responses that contain Set-Cookie headers, which are then returned to a different user. Because forms-based authentication uses a cookie to authenticate users, this can cause users to accidentally (or intentionally) impersonate another user by receiving a cookie from an intermediary proxy or cache that was not originally intended for them.