CoverYourASP --> utils/Email.asp" --> 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
127 active users
1883 visitors today
1585 pages today
how is this done?
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. 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...

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.html">(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


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

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


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...


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!


Qualify for Free Trade Magazines

Free subscriptions to industry leading publications for those who qualify!

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?