ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Send Email via Flash and PHP
http://www.actionscript.org/resources/articles/82/1/Send-Email-via-Flash-and-PHP/Page1.html
Jesse Stratford
Jesse lives and works in Melbourne Australia. He is the Cofounder of http://ActionScript.org. A Flash enthusiast, teacher, author, freelancer and speaker Jesse's main focus nowadays is managing http://ActionScript.org, but he enjoys participating actively in community and the wider Flash scene when he has time. 
By Jesse Stratford
Published on September 9, 2005
 
Tutorial details:
Written by: Jesse Stratford [email:jessestratford@actionscript.org]
Time: 20 minutes
Difficulty Level: Intermediate
Requirements: Flash 4+, PHP3+ support.
Topics Covered: custom functions, substring(), variable manipulation, loadVariablesNum and POST method, input text fields, delete(), mail() [PHP]

Demo: contact form
Tutorial details:
Written by: Jesse Stratford [email:jessestratford@actionscript.org]
Time: 20 minutes
Difficulty Level: Intermediate
Requirements: Flash 4+, PHP3+ support.
Topics Covered: custom functions, substring(), variable manipulation, loadVariablesNum and POST method, input text fields, delete(), mail() [PHP]

NOTE: This version doesn't do anything. It's just for show :o)

Click here to download the working source for this tutorial. (Flash 5, PC Zip file). Please note that this file uses the depreciated "add" syntax on Line 7 of Frame 2. Users of Flash 8 and higher will have to replace all occurrences of "add" with the "+" operator.

Welcome one and all! In this tutorial we're going to learn about sending mail using PHP and Flash. As always, my code is Flash 5 based but a half-knowledgible Flash 4 user could convert it back to ActionScript 4 quite easily. This simple tutorial will teach you how to send mail from your server to any email address around the world, with customized subjects, senders and messages. Applications include: Contact Us forms, like the sample above; Anonymous remailers; E-Card distribution things. The form I've used would allow you to append your site's footer at the end of each email sent if you were to be making an anonymous remailer for example.

Warning: I will only say this once: If you allow end-users to define the email address to which this email is to be sent you leave yourself open to all sorts of troubles. There are those users out there who would abuse an anonymous remailer service and any email they send is logged back to your web-server. So watch your back! (My example does not allow users to define he target email address to prevent such abuse).

We'll begin coding over the page...

The PHP Code
OK Let's get into it! This tutorial involves too much setting up for me to go through every step. Download the source file and open it up you will see the following:
  • Two frames, both with stop instances. The first contains the content, the second is a confirmation page.
  • Three text fields, whose variable names (from the top down) are subject, message, and from (notice I use italics because text fields store variables, thus their names are variables).
  • A "Send" button with some actions on it, (we'll get into that later).

If you open the PHP3 file in any plain text editor you will see it has the following code. Please note, this code is actually PHP4 code since most people seem to be using PHP4.x now and lots of people were having trouble with the older code:

[php]<?php
mail("yourem@ilhere.com", $_GET["subject"], $_GET["message"], "From: PHPMailer Reply-To: $_GET["from"] X-Mailer: PHP/" . phpversion());
?>[/php]

If you want the PHP3 code, it looks like this:

[php]<?php
mail("yourem@ilhere.com", $subject, $message, "From: PHPMailer Reply-To: $from X-Mailer: PHP/" . phpversion());
?>[/php]

Evaluation (What it does, and how):

<?php This tag marks the beginning of a PHP document. It tells the server we're tlaking in PHP now, not text or HTML
mail () A great little built-in PHP function. Can you guess what it does? (Hint: it doesn't make coffee).
youre@mailhere.com Replace this code with the email address you wish your form to send to.
$subject In PHP '$' denotes a variable. Thus this is the variable called subject. It has no value until we pass it one (which we'll learn about below)
$message The variable message.
PHPMailer This defines the sender of the email. If you're using this script for a comments or contact page I suggest you leave this code as is, or change it to something else obvious like "CommentsSubmitter" ( no spaces!! ). You could, if you like, adjust this to show the email address of the use who is sending the comments (so long as they can input their email in he Flash form) but that is covered in the next clause. I say you're better off leaving it as it, because you can readily identify all mail from "PHPMailer@yourdomain.com" (this is the address that will appear in your email viewing program), as comments submitted from your comments page. Furthermore, the next clause (Reply To) allows you to use your reply button as you normally would to reply to an email.
$from The variable from which we will define in the Flash file. This stores the email address of the sender and allows you to reply to their message.
?> Tells the server we've finished talking in PHP.

Basically, all you have to do is enter the email address you want these forms to be sent to and then save this PHP3 file (as a plain text file, maintaining the PHP3 extension).

Don't worry if this code seems a bit beyond you, it doesn't really need much edging. Let's move on...

The ActionScript Code
Open mailer.fla in Flash and double click the first frame to reveal the associated actions. You should see the following:

[as]stop ();
function lineAdapt () {
 message_send = message;
 while (msg_count<length(message)) {
  msg_count = msg_count+1;
  if ((substring(message_send, msg_count, 2)) eq " ") {
   message_send = (substring(message_send, 1, msg_count-2))
   +" "+(substring(message_send, msg_count+2, 
   (length(message_send))-msg_count+2));
  }
 }
 message = message_send;
 delete msg_count;
 delete message_send;
}[/as]

Note that some lines above have been spread across multiple lines for tutorial layout purposes.

Evaluation (Line by line):

  1. Stops the play head.
  2. Defines a custom function lineAdapt which will convert the flash carriage return marker ( " ") to the PHP equivalent (" "). This ensures that if the user types a comment with paragraph breaks, these breaks will be reflected in the email, rather than it being one very long line of text :o)
  3. Sets variable message_send to the value of message. This is a storage variable: we will adapt message_send rather than message because message is being displayed in a text box on screen and adapting it may cause strange visual output.
  4. Begins a loop which will continue until the newly created variable msg_count is greater than or equal to the length of the string contained in message.
  5. Incirments msg_count by 1.
  6. Conditional statement which checks if the 2 characters within the string message_send starting at letter number msg_count are equal to the string " ". If you type data into a text box in Flash and enter carriage returns, you wills see that the variable which stores that text fields value is adapted with a " " inserted where each carriage return should be, so we are looking for these markers using Line 6.
  7. If Line 6 returns True, replace the " " we just found with " " (which is the PHP equivalent of " "). This code looks complicated but it isn't really. Al it does it 'copies' the characters before and after the " ", the pastes those before, enters " " and pastes those after. The result is the equivalent string with " " instead of " ".
  8. Sets the variable message to the finalized version of message_send, which contains no " " markers. We do this because when we post our variables PHP will look for variables with the same name. Remember in the PHP code we refer to the variable messagenot message_send so we must make sure the correct variable holds the correct value.
  9. Deletes the counter variable for our loop from memory
  10. Deletes the temporary message_sendvariable we used for altering the new line markers.

Now if you examine the "Send" button you will see it has the following code:

[as]on (release) {
 if (subject eq "" or message eq "" or from eq "") {
  stop ();
 } else {
  lineAdapt();
  loadVariablesNum ("mail.php3", 0, "POST");
  gotoAndStop (2);
 }
}[/as]

Evaluation (Line by line):

  1. Says "Perform these actions when this button is clicked then released"
  2. Checks to see if any variable has no value. We don't want people sending us mail with no reply address for instance.
  3. Line 2 returns True, stop.
  4. Line 2 returns False, go on.
  5. Perform the predefined function lineAdapt () on our currently entered variables.
  6. Send variables, using the POST method, to our PHP script which will send the email off. (Note that you could also use LoadVars objects in place of LoadVariables if you wish to make this more synchornous. See the LoadVariables and LoadVars tutorial.)
  7. Go to the confirmation message and stop once the email is sent.

Almost done now...


Conclusion
Note in that we have used loadVariablesNum to "send" variables. We could just as easily have used GetURL but that would mean that our flash file would unload itself to open the PHP document. This way it runs in the background and the user never leaves your base movie.

The POST method is a form of communicate between files. Many of you would be familiar with the GET method which appends data tot he URL call of a file, (file.swf?variable=value). POST also communicates variables, however these variables are sent using hypertext protocol and not in the URL call. This is useful when the data you wish to submit is confidential (you don't want someone's password showing up in the URL!) or if your variables contain data that may cause errors. In this case, we cannot use GET because Flash reads the " " characters before sending off the call and subsequently tries to call a URL with multiple lines, (which obviously won't work).

That's it! Now you can upload both files to a web-server with PHP support and you should have no trouble getting it to work. These files do not require special permission to run and mail() is enabled on all half-decent PHP hosts. Remember that you can't run these files on your local disk unless you are running some sort of web-server with a PHP interpreter.

Thanks to Shai-Tan and massd on Efnet for their help with figuring out alternative ways to pass the damn new line markers!

Jesse Stratford [email:jessestratford@actionscript.org] is the Co-Master of ActionScript.org and a freelance Flash developer and teacher. He is based in Australia and enjoys all things Flash.

NB: If you have comments or feedback please feel free to email me, but please do not email me Flash questions; the forums are provided for that purpose and you will get a faster answer by posting you question there.

If you have found this tutorial helpful, I hope that you will take 30 seconds to visit The Hunger Site where, with just one click you can make a free donation of food to a starving person in a third-world country. We do not benefit financially from this action; it is purely an act of charity.
This tutorial is protected by International Intellectual Property Rights laws and may not be reproduced or redistributed in full or part, without the prior written consent of the author. Unauthorized reproduction of this tutorial or its contents may result in prosecution. I've worked hard on this tutorial, please don't steal it.