ASP
  Home arrow ASP arrow Sending Email From a Form in ASP
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP

Sending Email From a Form in ASP
By: James Shaw
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 63
    2003-05-19

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    James will now show you how one could use ASP to send out email messages. The components used in this article include CDONTS, JMail, ASPMail, and ASPEMail.

    How to send email from a form continues to be one of the top asked questions on search engines and ASP sites like mine.

    I've always offered you the source code for my forms (i.e. www.coveryourasp.com where you can download the entire site), but it's now time to step through the code with you and explain the code in more detail.

    Do you know how to write <form>'s with ASP? If not, read that first.

    Let's look at the first step after the form has been submitted - validating the inputs:

    // has the form been submitted?
    if ( bSubmitted )
    {
       // get the data from the form...
       sEmail = '' + Request.Form ( "email" );
       // validate the email address and moan if it fails
       if ( sEmail != '' && !IsValidEmail ( sEmail, hexVeLevelDns ) )
       {
          // pretend the form hasn't been sent yet
          bSubmitted = false;
       }
    }

    The email address is retrieved from the form, and if not blank, it is sent into IsValidEmail( ) to be validated.

    If the function returns false then I reset bSubmitted which causes the form to be re-displayed. But what does IsValidEmail( ) do?

    This function resides in the utils/email.asp Server Side Include. As you can see below, the function simply calls GetEmailRating( ), and displays a message if the function fails...

    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;
    }

    ...so we really have to look at GetEmailRating( ).

    var hexVeLevelSyntax = 1;
    var hexVeLevelDns = 2;
    var hexVeLevelSmtp = 3;
    function GetEmailRating ( sEmail, nLevel )
    {
       // simple syntax validation if no Hexillion component
       if ( !bUseHexillion )
       {
          if ( IsValidEmailSyntax ( sEmail ) )
             return hexVeLevelSyntax;
          return hexVeLevelBad;
       }
       //...use HexValidEmail

    To start with, I declare some global variables that are passed into these validation functions. Think of these as const's or enum's that are used to determine the level of confidence in the email address.

    Pass in hexVeLevelDns and Hexillion's cool HexValidEmail component will ensure that the domain in the email address exists. These constants are also used as return values from the functions.

    If we're not going to be taking advantage of HexValidEmail, and hence bUseHexillion is set to false in include/config.asp, we call a function that uses a regular expression to determine if the syntax of the email address is valid.

    Thanks again to Ed Courtenay for donating the regular expression used to validate the syntax. I'll leave you to explore that and the rest of the source code concerning email validation by viewing the entire utils/email.asp source code at the end of the article.

    For more information on HexValidEmail, and the 3 levels of validation it offers, see my live demonstration.

    Making up the email

    Having validated the email address, we need to make up the email and send it.

    // make up the message body
    var sBody = 'Message: "' + sMessage + '"\n\n';
    if ( sFromName != '' )
       sBody += 'From: "' + sFromName + '".\n';
    if ( sFromEmail != '' )
       sBody += 'Email: "' + sFromEmail + '".\n';

    The body of the email is very simple in this case - this form is sending the information to me, so I just declare an sBody variable and add each data on a new line ( \n is a linefeed character in JavaScript, C, C++, etc ).

    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';

    Then, I add some more information to the email such as the user agent (browser) that was used, and the IP address of the sender. All this data and much more is available from the Request.ServerVariables collection.

    Lastly, I add the time that the email was sent - note that this is server time, not the local client time...

    // send Email with our generic function
    SendEmail ( sFromEmail,
    'Feedback@'
    + sHostDomain, '', sSubject, sBody );

    ...and send the email, again using a function defined in the utils/email.asp SSI.

    Using the SendEmail( ) function

    This function is used to send all the emails throughout the site - so it's the only place that cares what email system you are using. Currently, 3 components are supported, but I'll support whatever else you ask for, within reason!

    • Microsofts' "Collaboration Data Objects for Windows NT Server", commonly known as CDONTS.

    • Persits' ASPEmail component.

    • ServerObjects' ASPMail component.

    • Dimac's w3 JMail component.

    The email component to use is specified by the nEmailServer setting in include/config.asp.

    Using CDONTS

    // 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 ( );

    Sending a simple email is very easy. This is literally the only code I've ever used. Start by creating an instance of the CDONTS.NewMail object, then fill in the relevant properties and call the Send( ) method.

    Some things to note though:

    • In order to specify multiple To, Cc or Bcc recipients of a message, simply separate the addresses with a semicolon...

    oMail.To = 'me@me.com;you@you.com;her@her.com'

    • Although the documentation says that you can send in an optional caption to the AttachFile method, it's never worked for me!

    • After the call to Send( ), the object is invalid. Do not try to use it again - you must create a new object.

    Using JMail

    To use JMail, set

    nEmailServer=nEmailJMAIL

    in include/config.asp. The SendEmail function will then execute the following code...

    // get a mail object
    oMail = Server.CreateObject ( "JMail.SMTPMail" );
    // setup the mail
    oMail.Silent = true;
    oMail.ServerAddress = 'mail.' + sHostDomain;
    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 ( );

    Again, very straightfoward code. The main difference from CDONTS is how multiple recipients are handled. JMail requires that the semicolon-separated list is split into an array, then fed into the AddRecipient method one at a time.

    Using ASPMail

    To use ASPMail, set nEmailServer=nEmailASPMAIL in include/config.asp. The SendEmail function will then execute the following code...

    // 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 = 'mail.' + sHostDomain;
    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 ( );

    Very similar to the JMail component, ASPMail also needs multiple recipients sent into an AddRecipient method individually.

    Take note of the comment above concerning the FromAddress and RemoteHost properties. I wasted some time tracking down that problem! ASPMail is actually the email system used on CoverYourASP.

    Using ASPEmail

    To use ASPEmail, set

    nEmailServer=nEmailASPEMAIL

    in include/config.asp. The SendEmail function will then execute the following code...

    // get a mail object
    oMail = Server.CreateObject ( "Persits.MailSender" );
    // setup the mail
    if ( sFromEmail == "" )
       oMail.From = 'Anonymous';
    else
       oMail.From = sFromEmail;
    oMail.Host = 'mail.' + sHostDomain;
    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 ( );

    As with all the third party components, I split the email address string into an array, and feed it into an Add method - for ASPEmail that's the AddAddress method.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More ASP Articles
    More By James Shaw

     

    IBM® developerWorks developerWorks - FREE Tools!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    NEW! A Layered approach to delivering security-rich Web applications

    As businesses grow increasingly dependent upon Web applications to provide services to customers, employees and partners, these complex applications become more difficult to secure. Although traditional security solutions protect Internet infrastructure layers, they do not guard against HTTP and HTML attacks. Many organizations that conduct security testing still deploy applications that allow attackers to manipulate their logic and wreak havoc on their business. To mitigate this risk, development and delivery teams must address Web application security throughout the lifecycle, addressing the many layers detailed in this paper.
    FREE! Go There Now!


    NEW! Applying lean thinking to the governance of software development

    Effective governance for lean development isn’t about command and control. Instead, the focus is on enabling the right behaviors and practices through collaborative and supportive techniques. Hear from Scott Ambler on how it is far more effective to motivate people to do the right thing than it is to force them to do so. Learn how to form a lightweight, collaboration-based framework that reflects the realities of modern IT organizations.
    FREE! Go There Now!


    NEW! BlammoSplat: Build a community Web site of OpenLaszlo animations, Part 3: The community animation

    Learn to enable users to both rate existing animations and to combine existing animations into new snippets. This is the third in a series of three tutorials that chronicle the building of a site that enables collaborative discussion and animation building using Domino and OpenLaszlo.
    FREE! Go There Now!


    NEW! Evaluate WebSphere Extended Deployment Compute Grid V6.1

    Visit IBM developerWorks to download a free trial version of WebSphere Extended Deployment Compute Grid, which lets you schedule, execute, and monitor batch jobs. Because online transaction processing and batch jobs execute simultaneously on the same server resources, you can avoid costly duplication of resources. Compute Grid supports job types of Java transactional batch, compute-intensive and a new type called "native execution", which enables non-Java workloads to run on distributed end points.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 1: Create a continuous build and integration environment

    Learn how to implement a build management system that uses and extends your existing automation technologies. This tutorial shows, step-by-step, how to install and configure IBM Rational Build Forge to manage builds for Jakarta Tomcat from source code.
    FREE! Go There Now!


    NEW! Integrating XML into Your Enterprise Using Data Federation

    XML has become a common way of storing business data as flat files and many data server vendors including IBM have provided ways to store this data within relational database systems. Increasingly collections of XML files are accessed like databases using an xQuery and other XML standard mechanisms. Businesses find the need to combine the traditional tabular structured data with XML formatted data. In this webcast, you’ll learn about IBM’s WebSphere Federation Server technology, which provides users with the ability to integrate these two data formats.
    FREE! Go There Now!


    NEW! Rational Asset Manager eKit

    Learn how to do more with your reusable assets with the free Rational Asset Manager eKit. The eKit includes demos on how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse. Plus you’ll find white papers and a Webcast that discuss the challenges of a Service Oriented Architecture and how Rational Asset Manager can provide quick and effective solutions.
    FREE! Go There Now!


    NEW! Rational Modeling Extension for Microsoft.Net

    Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms.
    FREE! Go There Now!


    NEW! Successful Change and Release Management for .NET

    Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP ARTICLES

    - Central Scoreboard with Flash and ASP
    - Calorie Counter Using WAP and ASP
    - Creating PGP-Encrypted E-Mails Using ASP
    - Be My Guest in ASP
    - Session Replacement in ASP
    - Securing ASP Data Access Credentials Using t...
    - The Not So Ordinary Address Book
    - Adding and Displaying Data Easily via ASP an...
    - Sending Email From a Form in ASP
    - Adding Member Services in ASP
    - Removing Unconfirmed Members
    - Trapping HTTP 500.100 - Internal Server Error
    - So Many Rows, So Little Time! - Case Study
    - XDO: An XML Engine Class for Classic ASP
    - Credit Card Fraud Prevention Using ASP and C...







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT