CoverYourASP --> "/MemberEdit.html" --> Source

Free membership

Join in the fun! Sign in
Member Services

Site navigation
Download the entire site!
Search my articles
Free Magazines
Browse the directory

Send me feedback
Buy my boxer shorts

Recommend this page
Printer-friendly page

Resources I recommend
Link to my site
Advertising slashed!
About your privacy
Legal stuff
Site statistics
12 active users
2298 visitors today
1999 pages today
(only part of today)
Tools I use

CoverYourASP
Copyright © 1999-2016 James Shaw.
All rights reserved.

ASP.NET Blog
RSS submissions
E-commerce

Now open source with SourceForge!

This page shows the actual source code used on this site. You can read the article that discusses this code here.

If this is the first CYA source code you've seen you should read this overview first.

Did you know you can download all the source code (and the database) of this site? Then get my newsletter to be emailed when I update the source code!

Please spread the word by recommending my site to your friends and colleagues!

This is JScript (server-side JavaScript), not the more common VBScript. More...

MemberEdit.asp

<!--#include file = "/include/Startup.html"-->

<%
// ============================================
// NOTE: all source code downloaded from CoverYourASP was written by
// James Shaw (unless stated otherwise), and is copyright (c) 2000-2002
// by James Shaw. You can use the code for any purpose, but do not
// publish or distribute the content in any way.
//
// See http://CoverYourASP.com/Legal.asp for up-to-date details.
// ============================================

// increment the parent articles counter
sIncArticlePage = '/MemberCode.html';

// output relevant meta tags
Init( "CoverYourASP member information" );

// output common top of page
Header( '<a href="/MemberServices.html">Member Services</a> --> Member Information' );

// output page content
Content ( );

// output common bottom of page
Footer( );

// ============================================
// the content of this page - every page has a function 'Content' that
// is called above.
// ============================================
function Content ( )
{
   Out ( '<td valign="top" class="content">' );

      // as always, the form is submitted to the same page so that
      // all the logic for the form is in the same place. you'll see
      // later where this is done.

      // the first thing to do is validate the data if the form has been
      // submitted - start by getting the data from the form
      var bSubmitted = ( Request.Form.Count>0 );
      var sName = '';
      var sEmail = '';
      var sPassword1 = '';
      var sPassword2 = '';

      // has the form been submitted?
      if ( bSubmitted )
      {
         // get the data from the form...
         sName = '' + Request.Form ( 'name' );
         sEmail = '' + Request.Form ( 'email' );
         sPassword1 = '' + Request.Form ( 'password1' );
         sPassword2 = '' + Request.Form ( 'password2' );

         var sError;

         // validate the data and moan if it fails
         if ( sName == '' || sEmail == '' || sPassword1 == '' || sPassword2 == '' )
         {
            sError = 'You must enter values for all items in the form.';
         }
         else
         {
            if ( !IsValidEmail ( sEmail, hexVeLevelDns ) )
            {
               // IsValidEmail displays the error, so I dont have to
               bSubmitted = false;
            }
            else
            {
               // validate the passwords match
               if ( sPassword1 != sPassword2 )
               {
                  sError = 'The passwords don\'t match!';
               }
               else
               {
                  // see if the email address already exists
                  DBInitConnection ( );

                  DBGetRecords ( 'SELECT MemberID FROM Members WHERE Email=\'' + DBEncode ( sEmail ) + '\'' );

                  var nID = ( oRecordSet.EOF ? 0 : oRecordSet ( 0 ) - 0 );

                  DBReleaseConnection ( );

                  // if it exists and I'm not logged in, then fail
                  // if it exists, I'm logged in and it's different, fail
                  if ( nID && ( !IsLoggedIn ( ) || nID != nMemberID ) )
                     sError = 'That email address is already used by a member!';
               }
            }
         }

         if ( sError != undefined )
         {
            Out ( '<font color="red" size=+1>' + sError + '</font><p>' );
            // pretend the form hasn't been sent yet
            bSubmitted = false;
         }
      }
      else
      {
         // get existing data if logged in already
         if ( IsLoggedIn ( ) )
         {
            sName = sMemberName;
            sEmail = sMemberEmail;
         }
      }

      // show the form if not submitted yet
      if ( !bSubmitted )
      {
         if ( IsLoggedIn ( ) )
         {
            Out ( 'Edit your member information below. All the fields are required. The changes will take effect immediately when you choose "Save Changes".' );
         }
         else
         {
            Out ( 'Start the registration process by filling out the form below. All the fields are required.' );

            Out ( '<p>"First name" is just used to greet you as you wander the site, and doesn\'t have to be unique. Just entering your first name is perfect!' );
         
            Out ( '<p>You will be sent a confirmation email at the email address you give - the email contains a special URL to use to complete the registration process. <a href="MemberHelp.asp#confirmemail">Read why this is done</a>.' );
         }

         Out ( '<center>' );

         // here's the form tag. the action attribute is the name of
         // the file that will be called with the answer - in this case
         // it's the same page. the method can be "post" to send the
         // form data 'behind the scenes' or "get" to appending the
         // data to the URL in the style page.asp?data1=a&data2=b
         //
         // use post most of the time - it's neater and "get" is limited
         // in the amount of data that can be sent.
         Out ( '<form action="/MemberEdit.html" method="post">' );

            // another table to line up the titles and inputs
            Out ( '<p><table bgcolor="#dddddd">' );

            Out ( '<tr><td align="right">' );
               Out ( 'Email:' );
            Out ( '</td><td align="left">' );
               // a simple text box. I'll reference it with the name "email"
               // and show 20 characters on the form. use the maxlength
               // attribute to set the maximum characters they can enter.
               // use value="some text" to pre-fill the input with data.
               //
               // IMPORTANT! using names that are commonly used by
               // other web sites has a big advantage to the user - IE
               // will drop down a list of previous answers, which they
               // can usually pick from rather than type in.
               Out ( '<input type="text" name="email" value="' + sEmail + '" size="20">' );
            Out ( '</td></tr>' );

            Out ( '<tr><td align="right">' );
               Out ( 'Password:' );
            Out ( '</td><td align="left">' );
               Out ( '<input type="password" name="password1" size="20">' );
            Out ( '</td></tr>' );

            Out ( '<tr><td align="right">' );
               Out ( 'Confirm:' );
            Out ( '</td><td align="left">' );
               Out ( '<input type="password" name="password2" size="20">' );
            Out ( '</td></tr>' );

            Out ( '<tr><td align="right">' );
               Out ( 'First name:' );
            Out ( '</td><td align="left">' );
               Out ( '<input type="text" name="name" value="' + sName + '" size="20">' );
            Out ( '</td></tr>' );

            Out ( '<tr><td>' );
               Out ( '&nbsp;' );
            Out ( '</td><td align="left">' );
               // type='submit" provides a submit button to perform the
               // form action. the button says "Submit" unless you override
               // with the value attribute.
               if ( IsLoggedIn ( ) )
                  Out ( '<input type="Submit" value=" Save changes ">' );
               else
                  Out ( '<input type="Submit" value="    Register    ">' );
            Out ( '</td></tr>' );
            Out ( '</table>' );

         Out ( '</form>' );

         Out ( '</center>' );

         Out ( '<p>Want to see how this page creates new members and edits existing ones? Click below to get all the source code!' );
         Out ( '<p><center><a href="ShowSource.asp?page=MemberEdit"><img src="images/source.gif" border=0></a></center>' );
      }
      else
      {
         // connect to the database
         DBInitConnection ( );

         if ( IsLoggedIn ( ) )
         {
            // update the login info
            oConnection.Execute ( 'UPDATE Members SET Name=\'' + DBEncode ( sName ) + '\',Email=\'' + DBEncode ( sEmail ) + '\',MemberPassword=\'' + DBEncode ( sPassword1 ) + '\' WHERE MemberID=' + nMemberID );

            DBReleaseConnection ( );

            // update the login info
            ValidateLogin ( sEmail, sPassword1, bMemberCookie );

            // redirect to front page
            Redirect ( '/default.html' );
         }
         else
         {
            // create the new member record
            oConnection.Execute ( 'INSERT INTO Members (Name,Email,MemberPassword,nPoints) VALUES (\'' + DBEncode ( sName ) + '\',\'' + DBEncode ( sEmail ) + '\',\'' + DBEncode ( sPassword1 ) + '\',0);' );

            // get back the member ID
            DBGetRecords ( 'SELECT MemberID FROM Members WHERE Email=\'' + DBEncode ( sEmail ) + '\'' );

            var nID = oRecordSet ( 0 ) - 0;

            DBReleaseConnection ( );

            // send Email with our generic function
            var sBody = 'Dear ' + sName + '\n\n';

            sBody += 'To complete the registration of your CoverYourASP membership account please click on the link below, or copy and paste the entire URL into your browser.\n\n';
            sBody += 'IMPORTANT: if the link below is wrapped onto two lines by your email software please copy from the "http" to the end of the number on the second line, then paste that into your browser.\n\n';
            sBody += 'http://CoverYourASP.com/C.asp?a=a&e=' + sEmail + '&i=' + nID + '\n\n';
            sBody += 'Regards,\n';
            sBody += '[email protected]\n';
            sBody += 'http://CoverYourASP.com/';

            sBody += '\n\nYou are receiving this email to confirm an action requested using your email address on my web site. If you did not request this please reply to this email. I will make sure you never receive an email from my site again. The request was made from ' + Request.ServerVariables ( 'REMOTE_ADDR' );

            SendEmail ( 'MemberServices@' + sHostDomain, sEmail, '', 'New membership', sBody );

            Out ( 'An email has been sent to ' + sEmail + ' - please follow the instructions in that email to complete your registration. Note that new members are removed if not confirmed within 10 days.' );
         }
      }

      ShowBottomBanner()

   Out ( '</td>' );
   Out ( '<td background="/images/gx/navgap.gif" valign="top">' );

      // show rotating banners
      ShowBanners ( 1 );

   Out ( '</td>' );
}
%>

utils/Database.asp

<%
// ============================================
// NOTE: all source code downloaded from CoverYourASP was written by
// James Shaw (unless stated otherwise), and is copyright (c) 2000-2002
// by James Shaw. You can use the code for any purpose, but do not
// publish or distribute the content in any way.
//
// See http://CoverYourASP.com/Legal.asp for up-to-date details.
// ============================================

// globals
var oConnection;
var oRecordSet;

// enums

// Connection.State and Recordset.State property
var adStateClosed = 0;         // the object is closed.
var adStateOpen = 1;             // the object is open.
var adStateConnecting = 2;   // the object is connecting.
var adStateExecuting = 4;      // the object is executing a command.
var adStateFetching = 8;         // the rows of the object are being fetched.

// Recordset.Cursor property
var adOpenUnspecified = -1;   // does not specify the type of cursor.
var adOpenForwardOnly = 0;   // (default) a forward-only cursor, i.e. you get only one pass thru the data!
var adOpenKeyset = 1;         // can go in any direction, and as a bonus you'll see changes other users make.  EXPENSIVE!
var adOpenDynamic = 2;      // as Keyset, but also you can see additions/deletions other users make.  EXPENSIVE!
var adOpenStatic = 3;         // can go in any direction, but read-only.

// Recordset.LockType property
var adLockUnspecified = -1;   // does not specify a type of lock.
var adLockReadOnly = 1;      // (default) guess!
var adLockPessimistic = 2;      // guaranteed to work
var adLockOptimistic = 3;      // records locked only when you call Update. fingers crossed
var adLockBatchOptimistic = 4;// required for batch update mode

var adCmdUnspecified = -1;   // Does not specify the command type argument.
var adCmdUnknown = 8;      // Default. Indicates that the type of command in the CommandText property is not known.
var adCmdText = 1;            // a textual definition of a command or stored procedure call.
var adCmdTable = 2;            // a table name whose columns are all returned by an internally generated SQL query.
var adCmdStoredProc = 4;      // a stored procedure name.
var adCmdFile = 256;            // a persisted Recordset.
var adCmdTableDirect = 512;   // a table name whose columns are all returned.

// SchemaEnum - specifies the type of schema Recordset to be retrieved by the OpenSchema method
var adSchemaTables = 20;      // returns the tables
var adSchemaForeignKeys = 27   // returns the foreign keys (relationships)
// ============================================
// example usage:
//      DBInitConnection ( );
//
//      DBGetRecords ( "SELECT * FROM Somewhere" );
//
//      ...use oRecordSet
//
//      DBReleaseRecords ( );      // optional step
//
//      DBGetRecords ( "SELECT * FROM SomewhereElse" );
//
//      ...use oRecordSet
//
//      DBReleaseRecords ( );      // optional step
//
//      DBReleaseConnection ( );
// ============================================

// ============================================
// initializes database variables for first use on page - leave it to the
// last possible second before calling this function
// ============================================
function DBInitConnection ( )
{
   // don't open it again if already opened!
   if ( oConnection != undefined )
      return;

   // don't bother trying to open if path is below SSI folders
   if ( -1 != sDBPath.indexOf ( '\\utils\\' ) || -1 != sDBPath.indexOf ( '\\include\\' ) )
      return;

   // you can open Recordset objects without a Connection object, but
   // it's far less efficient if you are opening multiple Recordsets.
   //
   // if you don't create a Connection object ADO creates a new one for
   // each new Recordset.Open, even if you use the same connection string.
   oConnection = Server.CreateObject( 'ADODB.Connection' );

   try
   {
      // open the database, catching any errors that occur
      oConnection.Open( sConnectionString );
   }
   catch ( e )
   {
      // display error message, and send email
      DatabaseException ( e );

      // quit running the script completely
      Response.End ( );
   }

   // create a Recordset
   oRecordSet = Server.CreateObject( 'ADODB.Recordset' );
}

// ============================================
// tidies up after DBInitConnection
// ============================================
function DBReleaseConnection ( )
{
   // don't release the connection if not connected!
   if ( oConnection == undefined )
      return;

   // close and delete the Recordset object
   DBReleaseRecords ( );

   oRecordSet = undefined;

   // Don't call Close if the Recordset failed to Open properly, i.e. its
   // State is still adStateClosed (0)
   if ( oConnection.State != adStateClosed )
      oConnection.Close();

   oConnection = undefined;
}

// ============================================
// executes the passed in SQL statement and returns a read-only
// forward-only oRecordSet object
// ============================================
function DBGetRecords ( sSQL )
{
   // if the Recordset is already open, close it
   DBReleaseRecords ( );

   // I could use oRecordSet = oConnection.Execute( sSQL ) here
   // but then I will always get back a read-only, forward-only cursor.
   // (admittedly this is the most used type, but still)

   // use oRecordSet.Open and I have far more control. For details
   // read the definitions of the enums at the top of this file.

   //Out ( sSQL );Response.Flush();

   try
   {
      // remember that this can fail if passed garbage, and hence the
      // Recordset will remain closed, State == adStateClosed
      if ( oConnection )
         oRecordSet.Open ( sSQL, oConnection, adOpenForwardOnly, adLockReadOnly );
   }
   catch ( e )
   {
      // display error message, and send email
      DatabaseException ( e );

      // quit running the script completely
      Response.End ( );
   }
}

// ============================================
// tidies up after DBGetRecords
// ============================================
function DBReleaseRecords ( )
{
   // when you have finished with an open Recordset object, call the
   // Close method to release its resources. You can call Open again.

   // Don't call Close if the Recordset failed to Open properly, i.e. its
   // State is still adStateClosed
   if ( oRecordSet != undefined && oRecordSet.State != adStateClosed )
      oRecordSet.Close();
}

// ============================================
// display exception message, but strip out database path if necessary
// ============================================
function DatabaseException ( e )
{
   Out ( '<table bgcolor="#ff0000" cellpadding="20"><tr><td>' );

      Out ( '<h4><font color="white">An error has occured while connecting to the database:</font></h4>' );

      var sMessage = e.description;

      // strip out the database path if present
      var nStart = sMessage.indexOf ( sDBPath )

      if ( -1 != nStart )
         sMessage = sMessage.slice ( 0, nStart ) + '[database path]' + sMessage.slice ( nStart + sDBPath.length );

      Out ( '<h4>&nbsp;&nbsp;&nbsp;"' + sMessage + '"</h4>' );

      Out ( '<h4><font color="white">Don\'t despair - this problem is probably well-documented in my <a href="http://CoverYourASP.com/Trouble.asp"><font color="white">trouble-shooting</font></a> section.</font></h4>' );

   Out ( '</td></tr></table>' );

   // make up the message body
   var sBody = 'The file "' + Request.ServerVariables ( "URL" ) + '?' + Request.QueryString ( ) + '" generated a database error\n\n';

   sBody += 'Referrer: "' + Request.ServerVariables ( "HTTP_REFERER" ) + '".\n';
   sBody += 'Browser: "' + Request.ServerVariables ( "HTTP_USER_AGENT" ) + '".\n';
   sBody += 'IP address: "' + Request.ServerVariables ( "REMOTE_ADDR" ) + '".\n';

   var dateToday = new Date();

   sBody += 'Time: "' + dateToday.getHours() + ':' + dateToday.getMinutes() + '".\n';

   sBody += sMessage;

   // send the email
   SendEmail ( 'Database.Exception', 'BadDB@' + sHostDomain, '', 'Reporting exception', sBody );
}

// ============================================
// are we using Jet engine db, or SQL server?
// ============================================
var bUsingJet;

function DBIsJet ( )
{
   // for efficiency, only work out if which I'm using
   // the first time I'm used on a page.
   if ( bUsingJet == undefined )
      bUsingJet = ( -1 != sDBDriver.indexOf ( '.Jet.' ) );

   return bUsingJet;
}

// ============================================
// wrap date in relevant delimeters depending on db engine
// ============================================
function DBWrapDate ( sDate )
{
   return ( DBIsJet ( ) ? '#' + sDate + '#' : '\'' + sDate + '\'' );
}

// ============================================
//
// ============================================
function DBIsNull ( )
{
   return ( DBIsJet ( ) ? 'Is Null' : '= null' );
}

// ============================================
// stores dropdown lists in Application variables for use with foreign keys
// ============================================
function DBGatherForeignKeys ( )
{
   if ( !Application ( 'GatheredForeignKeys' ) )
   {
      DBInitConnection ( );

      bDebug = true;

      oRecordSet = oConnection.OpenSchema ( adSchemaForeignKeys );

      var nFields = oRecordSet.Fields.Count;
      var bHeaders = false;

      var sRefTables = new Array;
      var sRefColumns = new Array;
      var sForeignTables = new Array;
      var sForeignColumns = new Array;
      var nForeign = 0;

      while ( !oRecordSet.EOF )
      {
         if ( IsDebug ( ) )
         {
            if ( !bHeaders )
            {
               Out ( '<table border="1"><tr>' );

               for ( i=0; i<nFields; i++ )
                  Out ( '<td>' + oRecordSet.Fields ( i ).Name + '</td>' );

               Out ( '</tr>' );

               bHeaders= true;
            }

            Out ( '<tr>' );

            for ( i=0; i<nFields; i++ )
               Out ( '<td>' + oRecordSet ( i ) + '</td>' );

            Out ( '</tr>' );
         }
      
         sRefTables [ nForeign ] = '' + oRecordSet ( 'FK_TABLE_NAME' );
         sRefColumns [ nForeign ] = '' + oRecordSet ( 'FK_COLUMN_NAME' );
         sForeignTables [ nForeign ] = '' + oRecordSet ( 'PK_TABLE_NAME' );
         sForeignColumns [ nForeign++ ] = '' + oRecordSet ( 'PK_COLUMN_NAME' );

         oRecordSet.MoveNext  ( );
      }

      if ( bHeaders )
         DebugOut ( '</table>' );

      for ( i=0; i<nForeign; i++ )
      {
         DBGetRecords ( 'SELECT * FROM ' + sForeignTables [ i ] );

         try
         {
            var sList = '<select name="' + sRefColumns [ i ] + '">';
            var sForeignColumn = sForeignColumns [ i ];

            while ( !oRecordSet.EOF )
            {
               // I assume that the second field is
               // the one to show in dropdown list
               sList += '<option value="' + oRecordSet ( sForeignColumn ) + '">' + oRecordSet ( 1 ) + '</option>';

               oRecordSet.MoveNext  ( );
            }

            sList += '</select>';

            Application ( sRefTables [ i ] + ':' + sRefColumns [ i ] ) = sList;

            DebugOut ( '<p>Created ' + sRefTables [ i ] + ':' + sRefColumns [ i ] );
            DebugOut ( '<p>' + sRefColumns [ i ] + '=' + sForeignTables [ i ] + ':' + sForeignColumn + ' output:'+ Server.HTMLEncode ( sList ) + sList );
         }
         catch ( e )
         {
            DebugOut ( '<p>Failed to create dropdown list for ' + sRefTables [ i ] + ':' + sRefColumns [ i ] );
         }
      }

      DBReleaseConnection ( );

      Application ( 'GatheredForeignKeys' ) = true;
   }
}

// ============================================
// display (not editable) recordset column value
// ============================================
function DBDisplayValue ( oRecordSet, sTableName, nColumn )
{
   var sColumnName = oRecordSet.Fields ( nColumn ).Name;
   var oValue = oRecordSet ( nColumn );

   // get dropdown list if a foreign key
   var sHTML = Application ( sTableName + ':' + sColumnName );

//   DebugOut ( '<p>Application (  ' + sTableName + ':' + sColumnName + '=' + sHTML );

   if ( sHTML )
   {
      // disable control
      var nIndex = sHTML.indexOf ( ' name' );

      if ( nIndex != -1 )
         sHTML = sHTML.slice ( 0, nIndex ) + ' disabled' + sHTML.slice ( nIndex );

      // place 'selected' in the correct spot
      var nIndex = sHTML.indexOf ( ' value="' + oValue );

      if ( nIndex != -1 )
         sHTML = sHTML.slice ( 0, nIndex ) + ' selected' + sHTML.slice ( nIndex );
   }
   else
   {
      // show prettier dates
      if ( oValue.Type == 7/*date*/ )
         sHTML = FormatDateDMY ( oValue );
      else
         sHTML = "" + Server.HTMLEncode ( '' + oValue );

      // for brevity show the first x characters only
      if ( sHTML.length > 35 )
         sHTML = sHTML.slice ( 0, 35 ) + '...';
   }

   return sHTML;
}

// ============================================
// display editable recordset column value
// ============================================
function DBEditValue ( oRecordSet, sTableName, nColumn )
{
   var sColumnName = oRecordSet.Fields ( nColumn ).Name;
   var oValue = oRecordSet ( nColumn );

   // get dropdown list if a foreign key
   var sHTML = Application ( sTableName + ':' + sColumnName );

//   DebugOut ( '<p>Application (  ' + sTableName + ':' + sColumnName + '=' + sHTML );

   if ( sHTML )
   {
      // place 'selected' in the correct spot
      var nIndex = sHTML.indexOf ( ' value="' + oValue );

      if ( nIndex != -1 )
         sHTML = sHTML.slice ( 0, nIndex ) + ' selected' + sHTML.slice ( nIndex );
   }
   else
   {
      // show prettier dates
      if ( oValue.Type == 7/*date*/ )
         sHTML = FormatDateDMY ( oValue );
      else
         sHTML = "" + Server.HTMLEncode ( '' + oValue );

      sHTML = '<input type="text" name="' + sColumnName + '" size="45" value="' + sHTML + '">';
   }

   return sHTML;
}

// ============================================
// return value with ' replaced by SQL-safe ''
// ============================================
function DBEncode ( sValue )
{
   return sValue.replace ( /\'/g, '\'\'' );
}
%>

utils/Email.asp

<%
// ============================================
// NOTE: all source code downloaded from CoverYourASP was written by
// James Shaw (unless stated otherwise), and is copyright (c) 2000-2002
// by James Shaw. You can use the code for any purpose, but do not
// publish or distribute the content in any way.
//
// See http://CoverYourASP.com/Legal.asp for up-to-date details.
// ============================================

// ============================================
// a simple email function to send email using different objects.
// ============================================
function SendEmail ( sFromEmail, sToEmail, sBccEmail, sSubject, sBody )
{
   if ( IsEmailBlocked ( sToEmail ) )
      return;

   var oMail;

   try
   {
      switch ( nEmailServer )
      {
      case nEmailCDO:
         
         // set config
         sch = "http://schemas.microsoft.com/cdo/configuration/";
         oConfig = Server.CreateObject ( "CDO.Configuration" );
         oConfig.Fields.Item(sch + "sendusing") = "2";
         oConfig.Fields.Item(sch + "smtpserver") = sMailServer;
         oConfig.Fields.Update();

         // get a mail object
         oMail = Server.CreateObject ( "CDO.Message" );
         oMail.Configuration = oConfig;

         // setup the mail
         if ( sFromEmail == "" )
            oMail.From = 'Anonymous';
         else
            oMail.From = sFromEmail;

         var sEmailList = sToEmail.split ( /[\s;,]/ );
         var nEmail;
         var sMail = '';

         for ( nEmail in sEmailList )
            sMail += sEmailList [ nEmail ] + ';';

         oMail.To = sMail;

         sEmailList = sBccEmail.split ( /[\s;,]/ );
         sMail = '';

         for ( nEmail in sEmailList )
            sMail += sEmailList [ nEmail ] + ';';

         oMail.Bcc = sMail;
         oMail.Subject = sSubject;
         oMail.TextBody = sBody;

         // send it
         oMail.Send ( );
         break;

      case nEmailCDONTS:
         // get a mail object
         oMail = Server.CreateObject ( "CDONTS.NewMail" );

         // setup the mail
         if ( sFromEmail == "" )
            oMail.From = 'Anonymous';
         else
            oMail.From = sFromEmail;

         var sEmailList = sToEmail.split ( /[\s;,]/ );
         var nEmail;
         var sMail = '';

         for ( nEmail in sEmailList )
            sMail += sEmailList [ nEmail ] + ';';

         oMail.To = sMail;

         sEmailList = sBccEmail.split ( /[\s;,]/ );
         sMail = '';

         for ( nEmail in sEmailList )
            sMail += sEmailList [ nEmail ] + ';';

         oMail.Bcc = sMail;
         oMail.Importance = 1;

         // if you want HTML mail...
         // uncomment the next two lines
         // oMail.BodyFormat = 0;
         // oMail.MailFormat = 0;

         // if you want to add an attachment...
         // uncomment the next line
         // oMail.AttachFile ( 'c://autoexec.bat' );

         oMail.Subject = sSubject;
         oMail.Body = sBody;

         // send it
         oMail.Send ( );
         break;

      case nEmailJMAIL:
         // get a mail object
         oMail = Server.CreateObject ( "JMail.SMTPMail" );

         // setup the mail
         oMail.Silent = true;
         oMail.ServerAddress = sMailServer;

         if ( sFromEmail == "" )
            oMail.Sender = oMail.ReplyTo = 'Anonymous';
         else
            oMail.Sender = oMail.ReplyTo = sFromEmail;

         var sEmailList = sToEmail.split ( /[\s;,]/ );
         var nEmail;

         for ( nEmail in sEmailList )
            oMail.AddRecipient ( sEmailList [ nEmail ] );

         sEmailList = sBccEmail.split ( /[\s;,]/ );

         for ( nEmail in sEmailList )
            oMail.AddRecipientBcc ( sEmailList [ nEmail ] );

         oMail.Subject = sSubject;
         oMail.Body = sBody;

         // send it
         oMail.Execute ( );
         break;

      case nEmailASPMAIL:
         // get a mail object
         oMail = Server.CreateObject ( "SMTPsvg.Mailer" );

         // setup the mail
         if ( sFromEmail == "" )
            oMail.ReplyTo = 'Anonymous';
         else
            oMail.ReplyTo = sFromEmail;

         // =========================
         // important - ASPMail only works if the
         // FromAddress is the same domain as
         // the RemoteHost domain
         // =========================
         oMail.FromAddress = 'james@' + sHostDomain;
         oMail.RemoteHost = sMailServer;

         var sEmailList = sToEmail.split ( /[\s;,]/ );
         var nEmail;

         for ( nEmail in sEmailList )
            oMail.AddRecipient ( "", sEmailList [ nEmail ] );

         sEmailList = sBccEmail.split ( /[\s;,]/ );

         for ( nEmail in sEmailList )
            oMail.AddBCC ( "", sEmailList [ nEmail ] );

         oMail.Subject = sSubject;
         oMail.BodyText = sBody;

         // send it
         oMail.SendMail ( );
         break;

      case nEmailASPEMAIL:
         // get a mail object
         oMail = Server.CreateObject ( "Persits.MailSender" );

         // setup the mail
         if ( sFromEmail == "" )
            oMail.From = 'Anonymous';
         else
            oMail.From = sFromEmail;

         oMail.Host = sMailServer;

         var sEmailList = sToEmail.split ( /[\s;,]/ );
         var nEmail;

         for ( nEmail in sEmailList )
            oMail.AddAddress ( sEmailList [ nEmail ] );

         sEmailList = sBccEmail.split ( /[\s;,]/ );

         for ( nEmail in sEmailList )
            oMail.AddBCC ( sEmailList [ nEmail ] );

         oMail.Subject = sSubject;
         oMail.Body = sBody;

         // send it
         oMail.Send ( );
         break;
      }
   }
   catch ( e )
   {
      EmailException ( e );
   }

   // release object
   oMail = null;
}

// ============================================
// display exception message
// ============================================
function EmailException ( e )
{
   Out ( '<table bgcolor="#ff0000" cellpadding="20"><tr><td>' );

      Out ( '<h4><font color="white">An error has occured while attempting to send email:</font></h4>' );

      Out ( '<h4>&nbsp;&nbsp;&nbsp;"' + e.description + '"</h4>' );

      Out ( '<h4><font color="white">If you are currently using CDONTS as your email component, try installing a trial version of one the third party products <a href="/ContactDescr4.html"><font color="white">shown here</font></font></a></h4>' );

   Out ( '</td></tr></table>' );
}

// ============================================
// validate email address to one of three levels : syntax, DNS, SMTP
//      syntax = the address looks valid
//      DNS = the domain exists, and can accept mail
//      SMTP = the domain mailserver agrees that the address is valid
//
// note that the time taken can be <1ms, 1-2s, 10s+ respectively!
//
// ============================================
// this uses the superb HexValidEmail COM object supplied by Hexillion
// visit them at http://www.Hexillion.com/ or see my demo at
// http://CoverYourASP.com/ValidateEmail.asp
// ============================================
var hexVeLevelBad = 0;
var hexVeLevelSyntax = 1;
var hexVeLevelDns = 2;
var hexVeLevelSmtp = 3;

function GetEmailRating ( sEmail, nLevel )
{
   // perform simple syntax validation for those without Hexillion
   // component
   if ( !bUseHexillion )
   {
      if ( IsValidEmailSyntax ( sEmail ) )
         return hexVeLevelSyntax;

      return hexVeLevelBad;
   }

   // =========================================   =
   // here's a simple version of this function, without any optimizations!
   /*
   // get an HexValidEmail object
   var oVE = Server.CreateObject( "HexValidEmail.Connection");

   // validate email address
   nRating = oVE.Validate( sEmail, nLevel );

   // release object
   oVE = null;
   
   return nRating;
   */
   
   // =========================================   =
   // here's the example I use, with some unnecessary DNS/SMTP
   // checks removed...
   var nRating = hexVeLevelBad;

   // lets do an obvious test first!
   if ( sEmail != "" &&
         nLevel >= hexVeLevelSyntax &&
         nLevel <= hexVeLevelSmtp )
   {
      // get an HexValidEmail object
      var oVE = Server.CreateObject( "HexValidEmail.Connection");

      // always check for syntax first
      nRating = oVE.Validate( sEmail, hexVeLevelSyntax );

      DebugOut ( 'syntax check: ' + nRating + '<p>' );

      // if I want more than syntax check, and...
      if ( nLevel > hexVeLevelSyntax &&
            //...I passed the syntax check
            hexVeLevelSyntax == nRating )
      {
         if ( nLevel == hexVeLevelDns )
         {
            // let's do some optimizing. first, rather than testing DNS for all domains
            // I'll hard-code some in a string - I KNOW these exist!
            var sGoodDomains =  " hotmail.com aol.com yahoo.com usa.net bigfoot.com earthlink.net mindspring.com ibm.net msn.com compuserve.com juno.com geocities.com excite.com altavista.com ibm.com microsoft.com netzero.net ";

            if ( -1 != sGoodDomains.indexOf ( ' ' + oVE.Domain + ' ' ) )
            {
               // I know this is a good domain, so I'll just return success
               nRating = hexVeLevelDns;
               DebugOut ( 'DNS check: known URL<p>' );
            }
            else
            {
               // I don't know this is ok, so I have to test
               nRating = oVE.Validate( sEmail, hexVeLevelDns );
               DebugOut ( 'DNS check: ' + nRating + '<p>' );
            }
         }
         else
         {
            if ( nLevel == hexVeLevelSmtp )
            {
               // more optimizing. again, I know some domains will accept
               // email sent to any username, so I don't bother checking
               var sDumbDomains = " aol.com yahoo.com bigfoot.com msn.com compuserve.com altavista.com microsoft.com netzero.net ";

               if ( -1 != sDumbDomains.indexOf ( ' ' + oVE.Domain + ' ' ) )
               {
                  // I won't get a sensible answer, so I'll just return success
                  nRating = hexVeLevelSmtp;
                  DebugOut ( 'SMTP check: known URL<p>' );
               }
               else
               {
                  // I don't know this is ok, so I have to test
                  nRating = oVE.Validate( sEmail, hexVeLevelSmtp );
                  DebugOut ( 'SMTP check: ' + nRating + '<p>' + Server.HTMLEncode ( oVE.SmtpSession ) + '<p>' );
               }
            }
         }
      }

      DebugOut ( 'Error check: ' + oVE.Error + '<p>' );

      // release object
      oVE = null;
   }
   
   return nRating;
}

// ============================================
// make sure that email isn't bad - DNS/SMTP timeouts are ok though
// ============================================
function IsValidEmail ( sEmail, nLevel )
{
   // test all email addresses sent in
   var sEmailList = sEmail.split ( /[\s;,]/ );
   var nEmail;

   for ( nEmail in sEmailList )
   {
      if ( hexVeLevelBad == GetEmailRating ( sEmailList [ nEmail ], nLevel ) )
      {
         Out ( '<center><b><font color="red">"' + sEmailList [ nEmail ] + '" is an invalid email address - try again!</font></b>' );
         Out ( '<br><a href="ValidateEmail.asp">(See how this email validation was done)</a></center><p>' );

         return false;
      }
   }

   return true;
}

// ============================================
// validate email address - syntax check with regular expressions
// (not used anymore - left for reference)
// ============================================
function IsValidEmailSyntax ( sEmail )
{
   // regular expression courtesy of [email protected]
   //
   // here's some documentation he provided:
   //
   //   \w+
   //      I am looking here for at least one 'word' - i.e. the 'fred' in
   //      [email protected]
   //
   //   ((-\w+)|(\.\w+)|(\_\w+))*
   //      This is probably the most complex section of  the whole
   //      expression. All I am looking for here are zero or more
   //      'words' prefixed by either a minus (-), dot (.) or
   //      underscore (_) all of which are legal characters in email
   //      addresses.
   //
   //   \@
   //      The one and only @ symbol used in the address
   //
   // [A-Za-z0-9]
   //      Now, I want at least one character that matches this rule
   //      (i.e. any letter from A-Z, uppercase or lowercase or a number
   //      from 0-9)
   //
   // ((.|-)[A-Za-z0-9]+)*
   //      This is saying that I can optionally accept more ranges of
   //      characters that match the rule above, prefixed with either a
   //      dot (.) or a minus (-). For example, this would match the
   //      .xyz portion of [email protected]
   //
   // \.
   //      A dot (.)
   //
   // [A-Za-z]{2,5}
   //      This final section ensures that the TLD (top level domain)
   //      portion of the email address is at least 2 characters long
   //      (as in .uk or .to) and no longer than 5 characters (to allow
   //      for .firm and .store)

   return ( sEmail.search( /\w+((-\w+)|(\.\w+)|(\_\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]{2,5}/ ) != -1);
}

// ============================================
// check that email hasn't been blocked to this address. send all data
// to webmaster (and optionally to blocked sender) if it has.
// ============================================
function IsEmailBlocked ( sEmail )
{
/*   // open database connection
   DBInitConnection ( );

   // is the email address in blocked list?
   DBGetRecords ( 'SELECT bSendCopy FROM BlockedEmail WHERE Email=\'' + sEmail + '\'' );


   if ( !oRecordSet.EOF )
   {
*/
   // make lowercase for the comparison
   var sTest = '>' + sEmail.toLowerCase ( ) + '<';

   if ( -1 != sBlockedEmails.indexOf ( sTest ) )
   {
      // should we copy to abused address?
//      var bSendCopy = oRecordSet ( 0 ) - 0;
      var bSendCopy = true;
      
      // this email is blocked, so send me an email
      var sBody = 'Someone has attempted to cause email to be sent to the email address "' + sEmail + '". As requested, the CoverYourASP site has blocked access to this email address. Below is all the information I could gather about the perpetrator:\n\n';
      
      sBody += 'HTTP_REFERER: ' +Request.ServerVariables ( 'HTTP_REFERER' ) + '\n';
      sBody += 'HTTP_USER_AGENT: ' +Request.ServerVariables ( 'HTTP_USER_AGENT' ) + '\n';
      sBody += 'LOGON_USER: ' +Request.ServerVariables ( 'LOGON_USER' ) + '\n';
      sBody += 'REMOTE_ADDR: ' +Request.ServerVariables ( 'REMOTE_ADDR' ) + '\n';
      sBody += 'REMOTE_HOST: ' +Request.ServerVariables ( 'REMOTE_HOST' ) + '\n';
      sBody += 'REMOTE_USER: ' +Request.ServerVariables ( 'REMOTE_USER' ) + '\n';
      sBody += 'SERVER TIME:' + new Date + '\n\n';

      sBody += 'If you have any questions about this email, or wish to stop receiving these notices of attempted abuse, please reply to this email.\n\nMember Services\nhttp://' + sHostDomain;

//      SendEmail ( 'MemberServices@' + sHostDomain, 'Abuse@' + sHostDomain, bSendCopy ? sEmail : '', 'Email blocked', sBody )

      return true;
   }
/*
   // release db connection
   DBReleaseConnection ( );
*/
   return false;
}
%>

Hopefully much of this is self-explanatory. If not, or if you see ways that I can improve the code, please drop me a line.

To see the source code for this page, click on the icon below.

Featured sponsor
My favorite resources


New Proposal Kit Professional 5.1
Brand yourself as a top professional: create quotes and amazing proposals and get many legal documents free!

The latter saved me 3 times the purchase price on the first day I owned it!


See my source code
wherever you see this icon...

You can also download the entire site source code for FREE!


Qualify for Free Trade Magazines

Free subscriptions to industry leading publications for those who qualify!


I share my content

Supporting ASPRSS

Do you need a quick and easy way to link to my articles? All the information you need is published with ASPRSS...

CoverYourASP Mugs, T-shirts, caps - even Boxer shorts...
I don't make a penny from these, but they're a lot of fun! Don't you need a new mouse mat?