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 / 64
    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!


    NEW! Calling all CC Power Users – and those that would like to be!

    Join this Rational Talks to You teleconference, featuring Paul Boustany and Mark Krasovich, to speak to the experts about becoming a Rational ClearCase power user. Get a chance to ask your questions and learn tips and tricks for using Rational ClearCase in Agile development
    FREE! Go There Now!


    NEW! IBM – Taking Web 2.0 to Work

    David Barnes, Lead Evangelist for IBM Emerging Internet Technologies will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! Accelerating Software Innovation on i on Power Systems

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, for an overview of Rational’s new software offerings and resources to help modernize and accelerate software innovation on i on Power Systems – while ensuring past application investments are protected and continue to grow. Learn how these solutions are helping customers extend their core i5/OS solutions toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!


    NEW! Don't wait! Try the Rational Application Developer (RAD) v7.5 open beta code today

    Download the Rational Application Developer (RAD) v7.5 open beta code and start developing applications for the JEE5 standard which features EJB3.0, JPA, JSF 1.2, JSP 2.1 and Servlet 2.5 standards. When you use this beta you will see how you can increase developer productivity for already existing applications with improved support for refactoring, as well as adding new features to existing applications. In addition, the beta provides tooling for JD Edwards, Oracle, SAP, Siebel and PeopleSoft to improve the developer productivity with these enterprise systems.
    FREE! Go There Now!


    NEW! Evaluate Rational Host Access Transformation Services (HATS) Toolkit V7.1

    Visit IBM developerWorks to download a free trial of the Rational Host Access Transformation Services (HATS) Toolkit. The HATS toolkit provides a set of plug-ins for the IBM Rational Software Delivery Platform to help you easily extend your legacy applications. HATS makes your 3270 and 5250 applications available as HTML through the most popular Web browsers, while converting your host screens to a Web look and feel and it also enables you to develop new Web, portal, and rich-client applications.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z

    IBM Enterprise Modernization solutions help organizations evolve core IT systems towards modern architectures and technologies—reducing the burden of maintenance and freeing up resources to develop new business requirements and capabilities. With the IBM Enterprise Modernization Sandbox for System z you can evaluate IBM Enterprise Modernization solutions focused on five key areas: Assets, Architectures, Skills, Processes and Infrastructures, and Investment. Each solution is based upon real customer experiences and offers a proven path to get you started with your modernization projects.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z: Architecture

    Analysts, architects, and developers who have existing COBOL or PL/I skills and want to extend those skills to deploy new workloads on the mainframe can use the IBM Enterprise Modernization Sandbox for System z to find hands-on walkthroughs of common real world scenarios. The scenarios provide examples of how to rapidly design, create, assemble, test, and deploy high-quality Web, Web services, portal, and SOA applications for IBM CICS, IBM IMS, and IBM WebSphere Application Server.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 2: Automate builds for a real-world Tomcat project

    Learn how Rational Build Forge can extend a simple compile and package build process by adding customization and deployment capability. Go from a manual method to automating: checking for code changes; getting the latest source; compiling and packaging; customizing; copying to and restarting a deployment server; and sending e-mail notification that a new version is available.
    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! Webcast: IBM Rational Build Forge - Beyond the Build

    The discipline of assembling and delivering software is maturing beyond standard developer-centric compile/test software builds. The end-to-end software development lifecycle is emerging as the new focus moves “Beyond the Build.” Join this on demand webcast to learn about methods for streamlining software delivery and key capabilities of the IBM Rational Build Forge framework for automating build and release management in environments of any size.
    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 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek