Flash Mail Form (with PHP)

So you want to create a mail form in Flash...

You need:

  • a PHP enabled server
  • basic understanding of Flash / ActionScript
  • very basic PHP knowledge
  • Flash MX or later

Creating a Flash Mail Form should be easy and can be resumed in 4 simple steps:

  1. collecting, validating and sending the data in/from Flash
  2. receiving and validating the data in the PHP script
  3. sending the email and a response back to Flash
  4. display the response in Flash

This article uses PHP but using another server side scripting language such as ColdFusion is pretty much the same.

I'll go into some detail on the PHP side as sometimes people have some difficulty with emails being sent, although debugging the script should be easy.

Lets start from the end - using the mail() function in PHP:

Although this function may take a lot of parameters and look complex at first, some of the parameters are optional. Here is the most basic use of mail() with only 3 parameters:

PHP:
  1. mail ($to, $subject, $message);

Where $to is the recipient's email address, $subject is the title of the email and $message is the body of the email.

In order to help you debug, it's really useful to know that the mail() function returns a value, a boolean - true or false.

First of all, just try the PHP script on its own to make sure the server can send emails and the script is running smoothly as expected.

Send an email to yourself:

PHP:
  1. $to = 'me@mydomain.com';
  2. $subject = 'test email';
  3. $message = 'this is the body of the email';
  4.  
  5. $sent = mail ($to, $subject, $message);
  6.  
  7. if ($sent)
  8. {
  9.  echo 'Working just fine. Email sent!';
  10. }
  11. else
  12. {
  13.  echo 'Oops! We have a problem. Something went wrong.';
  14. }

Save this script as email_test.php, upload it to your server and open it in the browser. The url should be something like http://mydomain.com/email_test.php.
You should see one of the two messages, hopefully the first, and receive an email.

Now that you can send emails lets prepare the script to receive variable value/name pairs from Flash.
Depending on your goal you may want to receive just one (a visitor's email, subscribing to a mailing list) or several variables (a visitor's name, email address, phone number, age, sex, ...).

In this example the visitor will have to provide the name, email and a comment. This means that the PHP script will expect 3 variables: name, email and comment.

The variables will be sent from Flash using the LoadVars Class, via POST so, we'll grab the variables from the $_POST array in the PHP script.

PHP:
  1. $name = $_POST['name'];
  2. $email = $_POST['email'];
  3. $comment = $_POST['comment'];

Then, we'll want to make sure that all the variables exist. If at least one of them doesn't, terminate the script and output an error.

PHP:
  1. if (!isset ($name) || $name == '')
  2. {
  3.     exit ('&message=Error! Name missing.&');
  4. }
  5.  
  6. if (!isset ($email) || $email == '')
  7. {
  8.     exit ('&message=Error! Email missing.&');
  9. }
  10.  
  11. if (!isset ($comment) || $comment == '')
  12. {
  13.     exit ('&message=Error! Comment missing.&');
  14. }

In this case, all the content will be added to the body of the email only so it should be pretty safe, but in other situations you'll also want to clean up the data a little bit.
You never know when someone is trying to do harm.
No user can be trusted.

For example, you may want to make sure that the email is really an email address; that the variables don't have white space around them or include strange (undesirable) characters; that they have at least or no more than a certain amount of characters, ...
See trim(), substr(), strip_tags(), addslashes(), str_len(),...

You may also want to encode the text as it may contain non English characters - see utf8_decode() and utf8_encode() - and convert \r to \n:

PHP:
  1. $comment = str_replace ("\r", "\n", $comment);

Lets send the email.
to and subject have predefined values - they don't have to - while message is a concatenation of the received variables.

PHP:
  1. $to = 'me@mydomain.com'; // replace with your email address
  2. $subject = 'New comment!';
  3.  
  4. $message = '';
  5. $message .= "\n";
  6. $message .= "Name: $name";
  7. $message .= "\n\n";
  8. $message .=  "E-mail: $email";
  9. $message .= "\n\n";
  10. $message .= "Comment:\n\n$comment";
  11.  
  12. $sent = mail ($to, $subject, $message);
  13.  
  14.  
  15. if ($sent)
  16. {
  17.  exit ('&message=Success! Email sent. Thank you very much for your comment.&');
  18. }
  19. else
  20. {
  21.  exit ('&message=Error! Sorry... Try again later please.&');
  22. }

Now it is time to head over to the Flash IDE and build the contact form.
You need:

  • an input text field for the name - name_txt
  • an input text field for the email - email_txt
  • a multiline input text field for the comment - comment_txt
  • a submit button - submit_btn
  • a dynamic text field for the status - status_txt

form

Grab the content of the input text fields and validate it.

Actionscript:
  1. submit_btn.onRelease = function()
  2. {   
  3.     var email = email_txt.text;
  4.     var name = name_txt.text;
  5.     var comment = comment_txt.text;
  6.    
  7.     // are all the fields filled?   
  8.     if (name == '') {
  9.         status_txt.text = "You need to fill in your Name.";
  10.         return;
  11.     }
  12.    
  13.     if (email == '') {
  14.         status_txt.text = "You need to fill in your E-mail.";
  15.         return;
  16.     }
  17.     // you should also validate the email address
  18.    
  19.     if (comment == '') {
  20.         status_txt.text = "Please, don't forget your Comment!";
  21.         return;
  22.     }
  23.    
  24.     // yes, all fields filled
  25.     sendEmail(name, email, comment);
  26.    
  27.     // sending data...
  28.     status_txt.text = "Processing mail form...";
  29.    
  30.     // prevent submitting again by disabling the button
  31.     this.enabled = false;   
  32. };

Store it in a LoadVars Object and send the data to the PHP script. Display the response in the status text field.

Actionscript:
  1. function sendEmail(name, email, comment)
  2. {   
  3.     var myData = new LoadVars();
  4.    
  5.     myData.name = name;
  6.     myData.email = email;
  7.     myData.comment = comment;
  8.    
  9.     myData.onLoad = function(ok) {
  10.         if (ok) {
  11.             status_txt.text = this.message;
  12.         } else {
  13.             status_txt.text = "There was an error. Try again later.";
  14.         }
  15.         submit_btn.enabled = true;
  16.     };
  17.    
  18.     myData.sendAndLoad('contactform.php', myData, 'POST')
  19. }

Sent!

You can download the files here.

From here, you can now explore the mail() function a bit further. Add some headers such as From:, or use the function again to send a confirmation email to the user.
The PHP manual is really useful! Don't forget the User Contributed Notes.

37 comments to Flash Mail Form (with PHP)

  • Great post!!! Now I am going to try to realize my own form. I will write a feedback soon.

    Thank you!!

  • Planche

    I’m using PHP mail() function to send an e-mail ( a send to friend function) on a website, the strange thing if you use a special character like portuguese characters (ã, ç etc.) you get an e-mail full of strange characters, like: relógio no catálogo de Verão

    I know it as something to do with the encoding, but didn’t manage to get it right.
    Any solution?

  • Take a look at the utf8_encode() function.

  • Will G

    Hi,

    Great work! I was wondering how to go about adding a checkbox that would let me know whether the person sending the comment wanted to be added to my mail list? maybe something – defaulted to checked – that added “add to mail list” in the body of the email after their message? I’ve been trying but I’m stumped!

    Thanks for any help!…Will

  • dan

    Hi there,

    I have set it up the way you have described but the email is not coming through, although i get a message that it has been sent sucessfully – what am i doing wrong?

    also, is there a way to validate the email to make sure it has an @ symbol and a . after it?

    Thanks in advance

  • Being that I’m a PHP novice, I wish you had included the beginning php tags on your emai_test.php example.

  • The emai_test.php does have opening and closing tags.
    The code on this page doesn’t because it is spread across several chunks of code.

    So, it’s recommended that you download the files and take a look at their code.

  • Hello again!

    the email_test.php, but the Flash page will not send along an email. I keep getting the “There was an error. Try again later.” Do you have any troubleshooting ideas on the Flash end? I tried both my own swf (using your instructions) and an swf from your file download.

    Albert

  • filipa fabrica

    i have two problems. 1) when i write in the input fields of my flash form i can´t see what’s being written, altough when i send the email all that i wrote is in the received mail.
    2) when i assign the headers i’m telling the way a i want to visualize my e-mail, right? that is if i write $headers = “De: ” . $_POST["nome"] .”, “. “\r\n”; in my email i should see something like:
    De: john, john@example.com. Instead in my email the information comes within the html tags like . It’s my first form maybe the questions are stupid:)

    thank u

  • Natalie

    Hey Nuno thank you so much for your php flash tutorial, not only was it well documented and easy to follow but it works perfectly – and you’ve helped me to create an email form that actually works ! thank you for such kind generosity and taking the time to share it with all us newbie php flashers! best of luck for all your future adventures! with thanks – Natalie

  • Hello Nunomira,

    I’ve been in a constant struggle for the last 3 days, I am getting the “Error opening URL” message in flash when I try to run a flash form that requests a php mailer file.

    I didn’t have that problem until this month, before that the flash form I used (within an interactive kiosk not the website form) was working fine for more than a year and now the email feature it stopped working, so I started to look for different flash forms and see if I got a newer one or something. So I found yours but it’s giving me the same error in flash, and if I upload it on my website, I get a “Error! Name missing” message in your form…any suggestions?

    Thanks!

  • Hi again nunomira,

    Just wanted to tell you that the form is working fine if I use it from the website, I think the “Error! Name missing” was a typo. But I’m still getting the “Error opening URL” message if I tried to run it locally by requesting the php file from the server (that is the way it was working from the kiosk program I mentioned) so I changed the line:
    myData.sendAndLoad(‘contactform.php’, myData, ‘POST’);

    to:
    myData.sendAndLoad(‘http://www.e-vendorslist.com/contactform.php’, myData, ‘POST’);

    And I get that error I mentioned. The form loaded in a website is of no use for my project, because the kiosk program runs locally that is why I’m testing it from flash.

    I’ll appreciate any help you can give :) Thanks again!

  • Awesome! I have been fighting with this for two days.(evenings, LATE evenings) I started my clients site with a general contact form using flash and php. The mailing portion would work fine, even a confirmation email to the visitor. But in flash, I would never get my “result” back to finish the movie with a sucessful message. It was supossed to work using this:
    //Confirmation is sent back to the Flash form that the process is complete
    $send_result = “Thank you. You will receive a confirmation email shortly.”;
    $send_answer = “answer=”;
    $send_answer .= rawurlencode($send_result);
    echo “$send_answer”;

    I have used this mailer before and new that it worked. I finally found the culprit to be Godaddy’s hosting. Go figure. Somehow the way they do things there really messes things up.
    But your method worked flawlessly with the Dynamic text method. I have used this before when clients wanted to change text from time to time, but never thought of using it in this manner. I knew there had to be another way of doing things to get around Godaddy’s mess. I will never use the above methos again!
    Awesome!
    Thanks!
    CaseyMx

  • Lasse

    Hi. I’m a beginner in Flash, so please help me. I want this mailform to be integratet in my site, and I don’t want it to be on a new page. How do i get this mailform into my site? I have tryed to paste the form into my site, create two layers and paste the actionscript into the layer, but it doesn’t work. The problem is that you can’t write in the textfields. What am I doing wrong? Kind regards, Lasse.

  • That is the info I was looking for! Thank you very much – you realy hepled me!

  • Rich Franks

    Is it possible to see the senders name in my Inbox instead of:

    “domain1688120

  • if does not work for sending mail in owner copy and same time customer copy plz help me comeplete script
    in my mail plz explain this

  • Holy crap! I’ve been working on a particularly difficult set-up for a few days now and so far (because GoDaddy’s hosting is so freakish) your code combo is the only one that’s actually worked for me. Thank you so much for sharing!

  • Jim

    Hi,
    May i know how to add the email validation into the php script?

  • alex cosmetico

    hi there, im trying using your tutorial under swishmax, and also with the conditions of godaddy. but unfourtunately with no result. i dont see any action being displayed in the status_txt dynamic textfield while pressing the button. also swishmax detects me the code:
    submit_btn.onRelease = function()…..

    as incorrect. looking in some other sources (http://www.swishtutor.com/)i found that i have to put the function under another syntaxis, that´s why im tryng the following:

    onSelfEvent (load)
    { submit_btn.onRelease = function(){
    var email = email_txt.text;
    var nombre = nombre_txt.text;
    var empresa = emp_txt.text;

    var articulo = art_txt.text;
    var material = mat_txt.text;

    var ancho = anch_txt.text;
    var alto = alt_txt.text;
    var largo = lar_txt.text;

    var estatico = est_txt.text;
    var dinamico = mov_txt.text;
    var carga = car_txt.text;
    var estiba = esti_txt.text;

    var termico = tra_txt.text;
    var humedad = hum_txt.text;
    var impresion = imp_txt.text;
    var extra1 = ext1_txt.text ;
    var extra2 = ext2_txt.text;
    var extra3 = ext3_txt.text;
    var extra4 = ext4_txt.text;
    var uso = uso_txt.text;

    sendEmail(nombre, email, empresa, articulo, material, ancho, alto, largo, estatico, dinamico, carga,
    estiba, termico,humedad, impresion, extra1, extra2, extra3, extra4, uso);

    status_txt.text = “Procesando…”;

    this.enabled = false; }
    }

    i have this code on my root, as you put in your example.
    and below this i have the other code:

    function sendEmail(name, email, comment)
    {
    var myData = new LoadVars();

    myData.name = nombre;
    myData.email = email;
    myData.empresa = empresa;
    myData.articulo = articulo;
    myData.material = material;
    myData.ancho = ancho;
    myData.alto = alto;
    myData.largo = largo;
    myData.estatico = estatico;
    myData.dinamico = dinamico;
    myData.carga = carga;
    myData.estiba= estiba;
    myData.termico= termico;
    myData.humedad= humedad;
    myData.impresion = impresion;
    myData.extra1= extra1;
    myData.extra2= extra2;
    myData.extra3= extra3;
    myData.extra4= extra4;
    myData.uso = uso;

    myData.onLoad = function(ok) {
    if (ok) {
    status_txt.text = this.message;
    } else {
    status_txt.text = “There was an error. Try again later.”;
    }
    submit_btn.enabled = true;
    };

    myData.sendAndLoad(‘formulario.php’, myData, ‘POST’);
    }

    i tried to check out if the hosting server might send emails and the php displays the message and the email is sent.

    the following is my php code:

    ANY ideas why this might not be working?? any help is appreciated.

  • alex cosmetico

    the following is my php code:

    $nombre = $_POST['nombre'];
    $email = $_POST['email'];
    $empresa = $_POST['empresa'];

    $articulo = $_POST['articulo'];
    $material = $_POST['material'];

    $ancho = $_POST['ancho'];
    $alto = $_POST['alto'];
    $largo = $_POST['largo'];

    $estatico = $_POST['estatico'];
    $dinamico = $_POST['dinamico'];
    $carga = $_POST['carga'];
    $estiba = $_POST['estiba'];

    $termico = $_POST['termico'];
    $humedad = $_POST['humedad'];
    $impresion = $_POST['impresion'];
    $extra1= $_POST['extra1'];
    $extra2= $_POST['extra2'];
    $extra3= $_POST['extra3'];
    $extra4= $_POST['extra4'];
    $uso= $_POST['uso'];

    if (!isset ($name) || $name == ”)
    {exit (‘&message=Error! Name missing.&’);}
    if (!isset ($email) || $email == ”)
    {exit (‘&message=Error! Email missing.&’);}

    $to = ‘medinabueno@gmail.com’;
    $subject = ‘Cotización via internet’;

    $message = ”;
    $message .= “\n”;
    $message .= “Nombre: $nombre”;
    $message .= “\n\n”;
    $message .= “E-mail: $email”;
    $message .= “\n\n”;
    $message .= “Empresa: $empresa”;
    $message .= “\n\n”;
    $message .= “Articulo: $articulo”;
    $message .= “\n\n”;
    $message .= “Material: $material”;
    $message .= “\n\n”;
    $message .= “Ancho: $ancho”;
    $message .= “\n\n”;
    $message .= “Alto: $alto”;
    $message .= “\n\n”;
    $message .= “Largo: $largo”;
    $message .= “\n\n”;
    $message .= “Peso estatico: $estatico”;
    $message .= “\n\n”;
    $message .= “Peso dinamico: $dinamico”;
    $message .= “\n\n”;
    $message .= “Peso carga: $carga”;
    $message .= “\n\n”;
    $message .= “Peso estiba: $estiba”;
    $message .= “\n\n”;
    $message .= “Ttermico: $termico”;
    $message .= “\n\n”;
    $message .= “Thumedad: $humedad”;
    $message .= “\n\n”;
    $message .= “Impresión: $impresion”;
    $message .= “\n\n”;
    $message .= “Extra: $extra1,extra2,extra3,extra4″;
    $message .= “\n\n”;
    $message .= “Uso: $uso”;

    $sent = mail ($nombre, $email , $empresa, $articulo, $material, $ancho, $alto, $largo, $estatico, $dinamico, $carga, $estiba,$termico,$humedad,$impresion,$extra1,$extra2,$extra3,$extra4,$uso);

    if ($sent)
    {exit (‘&message=Success! Email sent. Thank you very much for your comment.&’);}
    else
    { exit (‘&message=Error! Sorry… Try again later please.&’); }

  • nuno wat do you advise if am saving the input to a text document?and if my flash is more animated than this what do you advise. had a problem with the beginning code.

  • i have uploaded on my website and after a fill in everything, and I send it. An error message appears: Error! Name missing!
    Please explain me what can be the problem.
    My e-mail address is nandorbajko@yahoo.com
    It is wherry important for me, so please if you can help me.

  • Hi,
    Firs of all thanks for that tutorial… it’s the best on web :) However, I’m trying to make it works… but I can’t. I’m doing everything like you said, but when I;m trying to send email it’s saying: “There was an error. Try again later.”
    When I made .swf from your file and uploaded with php file to the server, it’s keeps saying the same… but test email works, so PHP works on my server. Any suggestions what should I check first ??

  • OK.. I’ve already figure out what was wrong, .php file wasn’t in the right folder :) thx again for tutorial

  • Chris

    Every time i test the form online i keep gettin the “error” message and i can’t work out what would be causing it?

    Any ideas?

  • THANK YOU VERY much. I am a niwit with flash , It took me weeks to find a working form with clear explanations !
    And then I found yours , a day and it runs perfectly!
    Know some little changes I build also a inputtext for a phone number with no problem ….
    Is it possible to make a clear all input button to make a clean form ?
    Again thank , maybe see how it workd on our site maybe you have some suggestions ? Can I give the input fields a ligth white color instead of the white ?
    Greetings from Holland
    Bob

  • Muhammad Iqbal

    thanks nunomira for this tutorial :)

  • I uploaded email_test.php with my email an it shows the “works just fine” screen. But no email appears on my inbox. Help please!

  • Hi,

    Since comments are closed on this page:
    http://www.nunomira.com/blog/?page_id=239
    I´ll leave my comments here full of gratitude regarding Write To Text File.

    It´s just awesome Nuno!
    I had been surfing, reading and trying lot´s of solutions, spending at least 2 days without getting any closer to a working solution.

    Then I more or less “stumbled” into your blog. And voilá everything worked just as promised. Now, I have been able to adjust and devlope your original files to suit my needs.

    So a big THANK YOU Nuno, for sharing your files and skills!
    I have learned a lot from them.

    :-)

    Jonnie

  • teresa

    Hi Nuno,

    I used your method to create a flash form exactly like your attached files and the form works well only in IE6, IE7 and Opera, but not in Firefox and Safari. I am not an expert in php, so I have no clue. Would you help me please?
    Thank you very much.

  • teresa

    Another question: is there a way to check if the input for email is valid or invalid? Thanks for your help in advance!
    Teresa

  • Hello Nuno,

    I tried downloading the files from the link above, but I got a not found page. Are these files still available? Please advice.

    Thanks,

    John

  • Aloha!!! Thanks very much!!! Good job! Thanks again. :-)

  • This is great tutorial with code thank you very much

  • Thanks!

    very useful information…you realy hepled me!

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>