• home
  • forum
  • my
  • kt
  • download
  • Sending mail from a Form in Flash with PHP, Perl, or ASP.

    Author: 2007-06-13 14:40:00 From:

    Introduction

    This tutorial shows you how to set up a form based e-mail system from within your Flash movie.  It describes how to set up the basic form components in the Flash movie as well as giving you the basic knowledge of how to set up either a PHP, Perl, or ASP script to handle the e-mail and have it sent to an address that you specify.  There are a ton of possible situations that you can use this type of application.   For example say you are offering products or services on your company's site - this system can be set up to enable you to send a customized e-mail specifically about the product or service in question, you can have it sent to multiple e-mail address's, or you can specify which product or service should be sent to which person in your company.  The possibilities are endless.  In order to provide you with the knowledge necessary to customize this application for all your needs, and to avoid using scripts that are set up by your server (aka formmail.pl etc) which add a ton of useless garbage to your data and make it hard to customize (and are just darn right confusing), this tutorial will walk you through all the basic's of writing the scripts yourself.  In order to keep everything as simple as possible and to make sure that you have a thorough understanding of the scripts - some security measures were left out.  It's up to you to provide these if you think it is necessary.  (I'll try to go over them as best as possible however).  This tutorial is intended for the advanced actionscript programmer and the novice PHP, Perl, or ASP programmer

    Included Files:

    •  SendMail.fla - the Flash source code - the form is set up as a Movie clip so you should be able to just cut-n-paste it into a new movie, make sure to give it an instance name of Mail if you follow this tutorial directly.  
    • snowMailPHP.php - The PHP source code file. 
    • snowMailPerl.cgi - The Perl source code file.
    • ASPMail.asp - the ASP source code file. 
    • subparseform.lib (No changes need to be made to this file - It just contains a subroutine for parsing the data from the Flash Movie) - Needed only for the Perl Script

    Overview

    This tutorial goes over 3 different types of scripts that do the exact same thing (PHP, Perl, and ASP).  Almost all servers allow the use of CGI scripts to be executed.  In this case the CGI script will be a Perl script.  The Perl script contains a couple of extra steps in the setup process.  So if your lucky enough to be able to run PHP on your server, it will make everything a lot easier in the long run - and is recommended instead of using Perl.  I have also included an ASP script and some comments on coding that.  They all work basically the same though.

    It is recommended that you follow along or at least test out the working example at: http://www.Flash-DB.com/SendMail/SendMail.html

    Part I - Setting up the Form in Flash

    Begin setting up the Flash form by creating text fields that will contain the information that you want to send.  The most basic fields are the Name, E-mail, and Comments fields.  Create each text field that you want to use as an "Input Text" field.  Then give each one a unique name.  Set the Max Chars option to a number  you think should be the maximum number of characters allowed for each field.

    To create hidden information that is passed to the script and eventually the e-mail,  all you have to do is set a variable.  For example you can set a unique Subject line in each e-mail you send by creating a variable named Subject. Another example would be if you wanted to set a different destination e-mail address for each occurrence of the form.  This is important if you want to be able to use the same exact form to be able to send different e-mails in different locations in the main Flash movie.  And then give it a value.  Here's an example:

    Subject = "This is the Subject";
    ToEmail = "joeBob@example.com";

    These variables must be located on the same level in the same movie clip as the rest of the text fields.   Additionally, the button that will eventually call the script and send the information to your server and on to the specified e-mail, must reside at that same level. 

    You can set up the form as either a separate movie clip located somewhere in the main movie or just on the _root level of the movie.  I would recommend setting it up as a self contained Movie clip so you could use it over and over in many different places in the movie - or in future projects.   To make everything easier, as mentioned earlier, try to keep all the text fields and hidden variables on the same level in the same Movie Clip.  This is however not necessary - you can use information, for example the e-mail address of the sender, from other parts of the script - you just have to get the paths right.  For example say you are sending the information from a movie clip called Mail and the user has already entered his/her e-mail in the main movie on the _root level.  You can automatically fill out the text field named E-mail by using the code Email = _root.Mail.Email; in the Movie Clip Mail.  Ok sounds confusing but it's really not, after a short time of messing around with it and trying different solutions you'll get it. 

    We will now create a dynamic text field named EmailStatus.  This text field will be used to show messages to the user on the progress or status of their e-mail.  You can also use this text field to display eror messages to the user, for example if they did not fill out one of the fields or they are not using a valid e-mail address. 

    For the next part of creating the form - create a button and label it SendMail or something similar.  Place this in the same Movie clip as the rest of your Input text Fields.  Then attach the following code to it:

    on (release) {
     if (!Email.length || Email.indexOf("@") == -1 || Email.indexOf(".") == -1) {
     EmailStatus = "Please enter a valid E-mail address";
     }
     else if (!FirstName.length) {
     EmailStatus = "Please Enter your name before Sending";
     }
     else if (!ToComments.length) {
     EmailStatus = "Please enter some text in you message";
     }
     else {
     loadVariablesNum ("snowMailPHP.php", "0", "Post");
     EmailStatus = "Sending... one Moment .. or two.. sometimes it's faster then other times";
     }
    }

    This code checks to make sure that all the input fields/variables have been filed out.  In the case of the Email, it checks to make sure that it is a valid e-mail address.  It checks for an @ symbol and a '.' symbol.  Hopefully by looking over the code you will be able to use this same method for any other input fields/variables you want to be sent to an e-mail address.  Note - this is not necessary, the only really important part of the above code is the "loadVariablesNum ("snowMailPHP.php", "0", "Post");" line.  Also note that this is the one line that you will have to change if you are going to be using something other then PHP to send the mail.  If you are using Perl, instead the line would read:  "loadVariablesNum ("http://www.yoursite.com/cgi-bin/snowMailPerl.cgi", "0", "Post");"  Or with ASP - "loadVariablesNum ("ASPMail.asp", "0", "Post");"

     Note: In the online example there are two extra fields named 'ToMail' and 'ToName' - These variables allow you to send an e-mail to anyone you want to.  Basically it's an anonymous e-mailer - There are a couple of precautions built in to discourage abuse of it in the actual example - but not in the attached downloadable documentation.  However you should not set up your Mail form in this way.   Always make the ToEmail hard coded into the script that you are using (or a hidden variable in the Mail Movie Clip). This will be shown later in this tutorial.   

    That's all there is to the Flash part - now on to the exciting part - setting up the server side scripts. 

    Part II - Setting up the server scripts

     Note: I have included three options in this tutorial - PHP, Perl, and ASP - You only need to use one.  This mainly depends on what type of server that you are using, and what is available on that server.  For Unix/Apache based servers, the Perl and PHP ones will work - with Perl being a little more universal.  For win NT/2000 servers the ASP and Perl scripts will work - some modifications will have to be made to the Perl script however.  To find out what type of server you are using and what scripting languages you have available for use, either view the documentation provided by your host, or call your server's tech support.  

    One thing to remember is that these script examples were written as educational examples, with simplicity and ease of use in mind.  They all work and can be immediately used, but extra security precautions should be taken if you are planning to use these scripts extensively on a public website, and have any reason to believe that someone would take advantage of them.  

    Option 1 - Setting up the PHP Script - to send mail with PHP

    The PHP option remains my favorite, it is easier to set up then the rest and PHP in general is easier to learn and understand for this type of application (Opinion).  Your server has to have either PHP 3 or 4 installed to be able to use the following. 

    The Code is listed below - each line of the code is then discussed.  Line numbers should not be included in the Actual script.   This script is also included with the download.  After you have made any changes, upload the script to the same directory that you will be running the Flash movie that contains the Mail form.  If you have the script in a different directory you will have to change the path in the loadvariables command (Send Mail Button)).  Note: The $ symbol in PHP indicates a scaler variable. 

    Note:  The User Entered variables in this case / example are - FirstName, Email, Company, ToComments, HearAbout - These values are from the flash movie.  No special parsing is required in PHP if it receives these variables then they are already set inside the script.  You may also want to add the stripslashes function in this script if you don't want slashes to be added to your output. An example of how to do this would be: $ToComments = stripslashes($ToComments);  
    1)  <&quest;
    2)  $ToEmail = "jeff@snowvids.com";
    3)  $ToName = "Jeff";
    4)  $ToSubject = "Example Mail from SendMail Tutorial";
    5)  $EmailBody = "Sent By: $FirstName\nSenders Email: $Email\nSenders Company: $Company\n\n
     Message Sent:\n$ToComments\n\nSender Heard About Site From: $HearAbout\n";
    6)  $EmailFooter="\nThis message was sent by: $FirstName from $REMOTE_ADDR If you feel that you
     recieved this e-mail by accident please contact us at www.yourSite.com";
    7)  $Message = $EmailBody.$EmailFooter;
    8)  mail($ToName." <".$ToEmail.">",$ToSubject, $Message, "From: ".$FirstName." <".$Email.">");
    9)  Print "_root.Mail.EmailStatus=Complete - Your mail has been sent";
    10)  &quest;>

     Open up the attached script called snowMailPHP.php and follow along - you can use any text editor to make any changes. 

    Line 1:  This just indicates the start of a php script.  In some cases it can be <?php or <?php3.

    Line 2:  This is one of the most important lines - this contains the e-mail address of the person that you want the message sent to.  In most cases this will be your own e-mail address.  I left it as my own for now - Be sure to change this to Your e-mail address.  

    Line 3:  This Line contains the Name of the person that you are sending this E-mail to.  In most cases you will hard code that into the script here, as shown.  You can also set this variable as a hidden variable in the Flash movie.  When you use the 'Post command' in conjunction with this script, the hidden variable will be sent along with the other variable values. 

    Line 4:  This Line sets the Subject line of the e-mail that you are sending.  

    Line 5:  This line combines the variables that were sent to the script by the 'Post command' when you used load variables from the Flash movie.  This is where you can format the look of your e-mail. 

    Line 6:  This adds some additional information to the bottom of the e-mail that you are sending.   You can add any extra info you want here.  Make sure to remember that everything has to be enclosed with " symbols and a ; symbol has to end the line.  Also note that the \n combo adds a return/new line to your e-mail.  

    Line 7:  This just combines the variables $EmailBody and $EmailFooter into one variable $Message.  

    Line 8:  This line is what actually sends the E-mail.  The php Function Mail is what does the job.  By enclosing the E-mail tags within <> symbols it creates something like a mailto function.  That way the person can respond to the e-mail directly.  

    Line 9:  This prints a message back to the flash movie.  In this case it sets the variable EmailStatus contained in the movie clip instance of Mail to a value of " Complete - Your mail has been sent".

    Line 10:  This just signifies the end of the PHP code. 

    Well those are the basic's of what you need to know to send mail from a form in Flash with PHP.  I hope that wasn't too confusing.

    Option 2 - Setting up the Perl Script to send Mail with Perl 

    The hardest part of using a cgi script is the setup and getting all your paths correctly.  I'll attempt to explain all this in as much detail as I can.  Along with some common errors that you can make, and how to avoid them.  First you'll have to change a couple things in the actual Perl script. You should only have to change Line 14 and possibly Line 1.  For the purpose of this example,  line numbers were included below.  In the actual script these should not be included.  In my opinion Perl is the hardest to work with out of all three options - but is the most universal in terms of allowed usage on servers.  There are some extra steps that you have to take in order to use a Perl script - If you have the choice I would recommend using either the PHP method or the ASP method.  (Notice the similarities between PHP and Perl - by learning one or the other you'll have a good knowledge of the one you don't know).

    Note:  The User Entered variables in this case / example are - FirstName, Email, Company, ToComments, HearAbout - These values have to use the $formdata function from the subparseform.lib.  Don't worry about this just make sure that any data that is entered by the user and posted to the script appears like this for example: $Email = $formdata{'Email'};

    Open up the attached Perl Script called "snowMailPerl.cgi" with notepad or any other text editor to follow along and make changes.  

    1)  #!/usr/bin/perl
    2)  require "subparseform.lib";
    3)  &Parse_Form;
    4)  $Email = $formdata{'Email'};
    5)  $FirstName = $formdata{'FirstName'};
    6)  $Company = $formdata{'Company'};
    7)  $ToComments = $formdata{'ToComments'};
    8) $HearAbout = $formdata{'HearAbout'};
    9) $ToEmail = "your\@emailaddress.com";
    10) $ToSubject = "Testing out Tutorial";
    11) $EmailBody = "Sent By: $FirstName\nSenders Email: $Email\nSenders Company: $Company\n\n
     Message Sent:\n$ToComments\n\nSender Heard About Site From: $HearAbout\n";
    12)  $EmailFooter="\nThis message was sent by: $FirstName from $REMOTE_ADDR If you feel that you
     recieved this e-mail by accident please contact us at www.yourSite.com";
    13) $Message = $EmailBody.$EmailFooter;
    14) open (MAIL, "|/usr/sbin/sendmail -t") || &ErrorMessage;
    15) print MAIL "To: $ToEmail \nFrom: $Email\n";
    16) print MAIL "Subject: $ToSubject\n";
    17) print MAIL "$Message\n";
    18) close (MAIL);
    19) print "Content-type: text/html\n\n";
    20) Print "_root.Mail.EmailStatus=Complete - Your mail has been sent";
    21) sub ErrorMessage {
    22) print "Content-type: text/html\n\n";
    23) print "_root.Mail.EmailStatus=Connection Failed Please Check the path to the text File";
    24) exit; }

    Line 1 - The first line contained in the script is called the shebang line.  You will notice that it has a # symbol followed by a ! symbol.  All other occurrences of the # symbol indicates a comment in a perl script.  The first line is a special case though.  It indicates the Path to a program on the server which can execute the script - Do not indent this or put it anywhere else other then the first line.  The program in most cases is something like Perl.exe.  Don't worry about that part though. Just make sure that the path is correct.  The most common path to perl is #!/usr/bin/perl On different types and different setups of servers it may be different however.  If your using an online host they should have the path to perl listed in their online documentation.  With Telnet you can use the command - 'Which Perl' from the prompt and it will display the path.  Change this line to reflect that path.

    Line 2 - of the code includes the library file "subparseform.lib" into the context of the script.  This file contains one subroutine that parses the incoming data.  You will never have to make any changes to the subparseform.lib file; it will work for any variable you can think of.  

    Line 3 - Just includes a subroutine from the "subparseform.lib" file.  There is only one subroutine in this file. You can include as many others though, and use them in the script in the same fashion.  As your scripts become more complex this is an easy way to keep track of everything.  

    Lines 4 to 8 - This just puts the incoming variables from the Flash movie into a form that you can work with.  It uses a function from the included "Parse_Form" subroutine.  Don't worry about this part, if you want more or less variables just use the same syntax and it'll work.

    Lines 9 - 10 - These lines contain the Email address that you are sending this e-mail message to - (Note this should always be hard coded in - it's really bad to allow anonymous e-mails from your site).  And the Subject line of the E-mail your sending.  This can also be included in the Flash Movie as a hidden field.  

    Line 11 - Places the incoming data into a nice readable format that is sent as the E-mail message body text. 

    Line 12 - This adds some additional information to the bottom of the e-mail that you are sending.   You can add any extra info you want here.  Make sure to remember that everything has to be enclosed with " symbols and a ; symbol has to end the line.  Also not that the \n combo adds a return / new Line to your e-mail.  

    Line 13 -  This just combines the variables $EmailBody and $EmailFooter into one variable $Message.  They period '.' combines the two. 

    Line 14 - This line opens a connection to SendMail (Sendmail is a e-mail program that is commonly used on most Unix systems) if your using a windows server this will be different - and you should ask your host for more information on how to send e-mails with this method.  The MAIL part is simply just a reference that you will be using.  The | symbol opens a connection to the SendMail program and allows you to send data to it.  The /usr/sbin/sendmail is the path to sendmail on your server.  This is the most common path.  With telnet you can check this path by typing "Which Sendmail" or "whereis SendMail" at the prompt, the path will be displayed directly after.  The -t flag follows directly after this (make sure there is a space in between the two).  The || &ErrorMessage indicates an error message if the path to the SendMail program is incorrect. 

    Lines 15-17 - This prints your data to the e-mail that you are sending.  The basic requirement for this is that you have a carriage return / new line after each - you do this by adding a \n after each part of the e-mail. 

    Line 18 - This closes the Connection to the Mail program.  

    Line 19-20 -  Prints out a success message which is read by the Flash movie when the script is done executing.

    Lines 21 to 24 - This is just an error message that you will get if the script was unable to open the Mail Program.  Just an easy way to check to see if the scripts working.

    Note on CGI vs Perl (I've found a lot of people get confused on this issue)

    CGI in itself is not a programming language, it is a way of doing things (Protocol). CGI stands for Common Gateway Interface. CGI is the normal way that browsers communicate with a web server, such as when Internet Explorer talks to a Web server.  Any script that sends or receives information from a server has to follow a set of standards set by the CGI protocol.  When people are talking about CGI scripts they are talking about a script that communicates with a web server.  They can be written in Perl or other types of programming languages.  Also all perl scripts do not have to be CGI scripts - Perl is actually a real programming language and is used for many purposes other then just the Internet. 

    These are the extra steps required when using the perl script.

    Upload:

    1) Upload the the files "snowMailPerl.cgi" and "subparseform.lib" to your cgi-bin on your server.  IMPORTANT: these must be uploaded in ASCII mode.  They will Not work if you upload them in binary mode.

    2) Upload your Flash swf  in Binary mode to any directory you want.

     Note: In the attached Flash .fla you will have to change the actionscript on the button that sends the mail from flash - to be able to use the Perl Script.  Change the loadvariables line to - loadVariablesNum ("http://www.yoursite.com/cgi-bin/snowMailPerl.cgi", "0", "Post");

    Changing the Permissions of the uploaded files on your server

    You need to change the permissions of the files "snowMailPerl.cgi".  The easiest way to do this is by using telnet to log-on to your account.  Their are other ways but this is the most basic - others may be easier but it would be impossible to explain them all (ask your host how to change permissions if you are having trouble with this).  One other option for changing the permissions of the script is by using an FTP program some allow you to change the permissions directly from there.  Once you have successfully entered your login name and password you will see the shell prompt.  You must then use the CD (Change directory) command to get to your cgi-bin.  You can then list all the files in that directory by typing in ls - this will list the files located in that directory.  You can type in ls -l to list all the files plus their permissions in that directory.   In most cases it will be something like this:

    %cd public_html
    %cd cgi-bin
    %ls -l
    total 2
    -rwxr-xr-x  1   July 31 15:30 snowMailPerl.cgi
    -rw-rw-r--  1   July 31 15:00 subparseform.lib
    % 

    I don't want to go into all the details on setting the file permissions so I'll just tell you what you need to do for this script. You need to change the permissions to 755.  You can do this with the following command.  

    %chmod 755 snowMailPerl.cgi
     Note: Permissions on a Unix server are based on 3 different category's - Owner, Group, and Other/everyone.  These are further broken down to 3 levels - Read, Write, and Execute. When you first upload a script it is usually set so that the Owner has read and write permission's and everyone else can just read.  Because you want others to be able to execute the script you have to change the permissions of the files.  Therefore you have to change the permission's of the script to 755 - so that everyone can execute it.  This mainly applies to Perl scripts and files that you need to write to on the server.  

    Option 3 - Setting up the ASP script to send mail with ASP

    The following script shows you how to send mail with ASP - it works similar to the two methods shown above. This script is from a Popular Windows 2000 Hosting service called innerhost.  The main difference between a PHP based mailing script and an ASP based mailing script is the use of a mailing object. Many Win NT/2K Hosts have the Smtpsvg.dll registered on their servers. If they do not, please check with the Host to see what sort of mail object they do use. The code below is pretty self-explanatory. On line 12, be sure to change ¡°mail.innerhost.com¡± to the SMTP mail server that your host provides. Also make sure to change lines 7-10 to your Name, Email, Subject etc.  This e-mail will work in the same manner as the previous two examples.

    1)   <&quest;
    2)  FirstName = Request.form("FirstName")
    3)  Email = Request.form("Email")
    4)  Company = Request.form("Company")
    5)  ToComments = Request.form("ToComments")
    6)  HearAbout = Request.form("HearAbout")
    7)  strName = "Your Name"
    8)  strEmail = "YourEmail@YourSite.com"
    9)  strSubject = "Tutorial Request Example Email"
    10) strBody = ToComments & HearAbout & Company
    11)  Set Mailer = Server.CreateObject("SMTPsvg.Mailer")
    12)  Mailer.RemoteHost = "mail.innerhost.com"
    13)  Mailer.FromName = FirstName
    14)  Mailer.FromAddress = Email
    15)  Mailer.AddRecipient strName, strEmail
    16)  Mailer.Subject = (strSubject)
    17)  Mailer.BodyText = strBody
    18)  if Mailer.SendMail then
    19)  Response.Write "_root.Mail.EmailStatus=Complete - Your mail has been sent"
     else
    20)  Response.Write "_root.Mail.EmailStatus=Failure - Your mail was not sent - errors"
    21)  Response.Write Mailer.Response
    22)  end if
    23)  &quest;>

    Line 1 -  Starts the ASP script

    Lines 2  to 6 - This captures the data sent with the header information from the post command and puts it into a format that the asp script can use. 

    Lines 7 to 8 - Sets the Name and E-mail address to which you are sending this information to.  Make sure to change this to your own name and e-mail if you are going to be receiving this e-mail (or to the person that is).  

    Line 9 - This sets the subject line of the message that you are sending.

    Line 10 - Formats the contents of the inputted information into the Body of the Email.

    Line 11 - This sets the Mailing object, that enables the script to send the E-mail.  This may be different, SMTPsvg.Mailer is the most common Mailing Object but can be different depending on your server. 

    Line 12 - Make sure to change this according to your Host.

    Lines 13 to 17 - Sets up the e-mail and assigns each different E-mail field it's previously defined vale. 

    Lines 18 to 22 - Just checks to see if the mail was sent - If it was it prints out a Complete/success message back to the Flash movie.  If it was not successful then an error message is sent back to the flash movie.  

    And that's about it with the ASP section - Remember that because of the wide variety of server setups and the ways that individual hosting services set up their server, this will not work all the time.  I tried to give the most general widely used examples - but you may have to contact your host for further information. 

    Conclusion

    That's about it - Hopefully that gave you some insight on how to send a form e-mail from Flash.  These three solutions should enable you to use this method from any server with only a couple of modifications.  Please note that if you can't get these to work right away don't worry about it, keep trying.  It takes some time to become familiar with the topics covered in this tutorial.  The best way to learn this information is to keep trying and setting up small examples for yourself.  Eventually it will become second nature - and you'll wonder why you ever used the mailto function.  

    -Jeffrey F. Hill  
    www.flash-db.com

    » Level Advanced

    Added: : 2001-08-27
    Rating: 8.80 Votes: 312
    Hits: 12745
    » Author
    No details available.
    » Download
    Download the files used in this tutorial.
    Download (67 kb)

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      3D (20)
      Math Physics (14)
      3rd Party (5)
      Navigation (60)
      Actionscripting (26)
      Optimization (16)
      Animation (32)
      Projector (9)
      Audio (46)
      Special Effects (112)
      Backend (25)
      Text Effects (65)
      Drawing (18)
      Tips and Techniques (41)
      Dynamic Content (25)
      Tricks (6)
      Games (66)
      Utilities (19)
      Getting Started (71)
      Video (10)
      Interactivity (21)
      Web Design (22)

    New

    Hot