Create an email form in flex with php
May 6th, 2009 in Flex | 53 CommentsThe following code demonstrates how to build an email form that supports some validation and that send the email by using a php script.
1. First we create a form that contains fields for the user to fill :
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"> <mx:Panel height="401" width="400" layout="absolute" title="Contact us"> <mx:Form x="9" y="10" width="360"> <mx:FormItem label="Name :"> <mx:TextInput id="senderName"/> </mx:FormItem> <mx:FormItem label="Email :"> <mx:TextInput id="senderEmail"/> </mx:FormItem> <mx:FormItem label="Subject :"> <mx:TextInput id="emailSubject"/> </mx:FormItem> <mx:FormItem label="Message :"> <mx:TextArea id="emailMessage" height="132" width="213"/> </mx:FormItem> </mx:Form> <mx:Button label="Send" x="138" y="274"/> <mx:Label id="resultLabel" x="212" y="276"/> </mx:Panel> </mx:Application>
2. To send the email we use the following php script :
<?php $senderName = $_POST['senderName']; $senderEmail = $_POST['senderEmail']; $sendToEmail = "yourmail@riacodes.com"; $subject = $_POST['emailSubject']; $emailMessage = $_POST['emailMessage']; $recipient = "$sendToEmail"; $headers = "From: $senderEmail "; $message = "From: $senderName, \nEmail Address: $senderEmail\nSubject: $subject\n\nMessage: $emailMessage"; $message = stripslashes($message); mail($recipient, $subject, $message, $headers) ?>
Replace the value of the variable $sendToEmail with your mail.
3. This php script will be called by putting its url inside an HTTPService.
<mx:HTTPService id="emailService" url="php/mail.php" method="POST" resultFormat="xml" useProxy="false"/>
4. Next we add some validation to check the fields that the user has filled. To do so we use the EmailValidator and StringValidator :
<mx:EmailValidator id="mailValidator"
source="{senderEmail}" property="text"
requiredFieldError="Enter your email" required="true" />
<mx:StringValidator id="nameValidator"
source="{senderName}" property="text"
requiredFieldError="Enter your name" required="true"/>
<mx:StringValidator id="emailValidator"
source="{emailMessage}" property="text"
requiredFieldError="Enter your message" required="true"/>
5. Now we add a function when the send button is clicked.
<mx:Button label="Send" click="sendMail()" x="138" y="274"/>
The function needs to check if the validation criteria are fullfilled. If it is OK, we get the value of fields and we call the send method of the HTTPService to call the php script to which we pass parameters.
If validation is not Ok, we display an error.
private function sendMail():void{
var _senderName:String = senderName.text;
var _senderEmail:String = senderEmail.text;
var _emailMessage:String = emailMessage.text;
var _emailSubject:String = emailSubject.text;
var evValidMail:ValidationResultEvent = mailValidator.validate();
var evValidName:ValidationResultEvent = nameValidator.validate();
var evValidMessage : ValidationResultEvent = mailValidator.validate();
if (evValidMail.type == ValidationResultEvent.VALID
&& evValidName.type == ValidationResultEvent.VALID
&& evValidMessage.type == ValidationResultEvent.VALID){
emailService.send({senderName: _senderName, senderEmail:_senderEmail,
emailSubject:_emailSubject, emailMessage: _emailMessage});
}
else{
resultLabel.text="There are Form errors";
resultLabel.setStyle("styleName", "invalid");
}
}
Note that the names of the parameters that we give (senderName, senderEmail, emailSubject, emailMessage) are those that we call in the php script. Example: $_POST['senderName'];
6. Finally we call the emailResult function when the HTTPService triggers a result event.
<mx:HTTPService id="emailService" url="php/mail.php" method="POST" resultFormat="xml" useProxy="false" result="emailResult()"/>
The emailResult function display a message to the user that his mail has been sent and clear the form.
private function emailResult():void{
Alert.show("Thank you for your submission ");
clearForm();
}
private function clearForm():void{
resultLabel.text="";
emailSubject.text="";
emailMessage.text="";
}
7. To finish we add some css to make the app more appealing. (The image for the background was taken from interfacelift.com/wallpaper_beta/details/1879/bellows.html)
The final code is beneath:
MXML code
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
<mx:Style source="css/style.css"/>
<mx:Script>
<![CDATA[
import mx.events.ValidationResultEvent;
import mx.controls.Alert;
private function sendMail():void{
var _senderName:String = senderName.text;
var _senderEmail:String = senderEmail.text;
var _emailMessage:String = emailMessage.text;
var _emailSubject:String = emailSubject.text;
var evValidMail:ValidationResultEvent = mailValidator.validate();
var evValidName:ValidationResultEvent = nameValidator.validate();
var evValidMessage : ValidationResultEvent = mailValidator.validate();
if (evValidMail.type == ValidationResultEvent.VALID
&& evValidName.type == ValidationResultEvent.VALID
&& evValidMessage.type == ValidationResultEvent.VALID){
emailService.send({senderName: _senderName, senderEmail:_senderEmail, emailSubject:_emailSubject, emailMessage: _emailMessage});
}
else{
resultLabel.text="There are Form errors";
resultLabel.setStyle("styleName", "invalid");
}
}
private function emailResult():void{
Alert.show("Thank you for your submission ");
clearForm();
}
private function clearForm():void{
resultLabel.text="";
emailSubject.text="";
emailMessage.text="";
}
]]>
</mx:Script>
<mx:HTTPService id="emailService" url="php/mail.php" method="POST" resultFormat="xml" result="emailResult()" useProxy="false"/>
<mx:EmailValidator id="mailValidator"
source="{senderEmail}" property="text"
requiredFieldError="Enter your email" required="true" />
<mx:StringValidator id="nameValidator"
source="{senderName}" property="text"
requiredFieldError="Enter your name" required="true"/>
<mx:StringValidator id="emailValidator"
source="{emailMessage}" property="text"
requiredFieldError="Enter your message" required="true"/>
<mx:Panel height="401" width="400" layout="absolute" title="Contact us">
<mx:Form x="9" y="10" width="360">
<mx:FormItem label="Name :">
<mx:TextInput id="senderName"/>
</mx:FormItem>
<mx:FormItem label="Email :">
<mx:TextInput id="senderEmail"/>
</mx:FormItem>
<mx:FormItem label="Subject :">
<mx:TextInput id="emailSubject"/>
</mx:FormItem>
<mx:FormItem label="Message :">
<mx:TextArea id="emailMessage" height="132" width="213"/>
</mx:FormItem>
</mx:Form>
<mx:Button label="Send" click="sendMail()" x="138" y="274"/>
<mx:Label id="resultLabel" x="212" y="276"/>
</mx:Panel>
</mx:Application>
PHP code
<?php $senderName = $_POST['senderName']; $senderEmail = $_POST['senderEmail']; $sendToEmail = "yourmail@riacodes.com"; $subject = $_POST['emailSubject']; $emailMessage = $_POST['emailMessage']; $recipient = "$sendToEmail"; $headers = "From: $senderEmail "; $message = "From: $senderName, \nEmail Address: $senderEmail\nSubject: $subject\n\nMessage: $emailMessage"; $message = stripslashes($message); mail($recipient, $subject, $message, $headers) ?>
CSS code
Application
{
font-family: arial;
font-size: 11;
color: #333333;
background-gradient-alphas: 0, 0;
background-color: #666666;
theme-color: #333333;
font-weight: normal;
background-image: Embed("assets/background.jpg");
background-size: "100%";
}
.invalid{
color:#990000;
}

Jun 2nd, 2009
Very nice article, It helped me for my application. Thanks mate.
Jun 7th, 2009
thanks very nice
Jun 29th, 2009
I was able to get it to work. Thanks. But…
Can this be called using a button? I have it on main page, and I want to have some feedback when a user clicks on the button. I currently have this code below, but I keep getting errors when I try and to run it.
1137:’ Inocorrect number of arguments
1067: Implicit coercion of a value of type Function
1046: Type was not found or was not a compile-time constant
private function ContactbyEmail():void
{
var email:ContactbyEmail = ContactbyEmail(PopUpManager.createPopUp(this,ContactbyEmail,true,null));
PopUpManager.centerPopUp(email);
}
Thanks in advance.
Aug 4th, 2009
Thanks a lot! Great code, implements fast, no errors. This is fast & furious.
Aug 5th, 2009
I also used this code and it works great with my PHP code! Thanks again! This was awesome as what the video player tutorial.
Aug 7th, 2009
Hi All !
I Am facing one problem , its now working for me but am getting the thanks page ,but not getting the mail, can any one help regarding this
thanks in advance
Aug 13th, 2009
Hello, Thanks for the tutorial. But I have a problem. I can send à mail with xour exemple. I don’t know where I put your script php .
Thank u.
Aug 17th, 2009
Hi
Great Tutorial.
I was wondering how i could modify the script so that i could send to multiple parties?
Regards
Steve
Aug 25th, 2009
[...] Create an email form in flex with php | RiaCodes http://www.riacodes.com/flex/create-an-email-form-in-flex-with-php – view page – cached RiaCodes is a site dedicated to web developers and designers about Flash, Flex and Air technologies. — From the page [...]
Sep 2nd, 2009
Great stuff…
Sep 12th, 2009
Great information – thank you. I’m creating php scripts for several friends’ websites and have two questions:
1. How do I create blank lines between the information lines in the e-mail that gets sent by the php script?
2. How can I enter text to be sent along in the body of each php e-mail, e.g. a reminder to respond to the entered e-mail address and not hit ‘reply’.
Thanks!
Sep 14th, 2009
How do you alter the code to actually send an email?
At the moment, it does nothing but pop up a message box thanking you for your submission.
Sep 22nd, 2009
Thankx u saved me lot of time
Works great
Oct 27th, 2009
Thank you very much for the tutorial.
I’m having a bit of trouble getting it to work. I’m on a mac using MAMP with a localhost. When I submit an e-mail it returns “Thank you for your submission”. But, I can’t find the message I sent. I’m trying to send the e-mail to my yahoo e-mail. Is that possible?
I changed the e-mail address in the php file to my address.
What am I doing wrong? Any suggestions?
Thank you!
-Chris
Oct 28th, 2009
Just to follow-up on my previous message:
I moved the e-mail form into a viewStack which is activated by a button. I’m not getting any errors and I’m getting the “Thank you for your submission” message. I used Charles Web Debugging Proxy and it looked okay.
But, when I check my e-mail, the message didn’t arrive.
My problem sounds similar to Alison’s.
If anyone has any suggestions that I can try, please let me know. I’m stumped.
Again, thank you RIA Codes for putting together this tutorial.
All the best,
Chris
Oct 29th, 2009
Hi,
Will this tutorial run on a localhost or do you have to put it on a remote server in order to test it?
Thanks,
Chris
Oct 30th, 2009
Hi.
how to use httpservice many times. (not just to validate login)
i mean not just to send data once..
what about to sessions?. or just sending email form, register form, session zone etc. all in the aplication.
im taking a look with amfphp/postgres.
amfphp as gateway.
any idea?
thanks a lot.
Oct 30th, 2009
I think that the problem is the configuration of Postfix on my localhost. If anyone knows of a good tutorial on configuring postfix, please let me know.
Oct 30th, 2009
Okay,
I figured it out. I had to configure MAMP Pro’s Postfix.
In MAMP Pro’s Postfix form where it reads “domain of outgoing mail”, I should have had vzavenue.net instead of verizon.net. Then click the “Change Postfix Configuration” button and you’re done. I didn’t need to change anything else.
It turned out that my internet service is provided by Verizon’s vzavenue not plain old Verizon.
A simple problem that took me a week to figure out!
Hope that this helps some other people.
-Chris
Dec 30th, 2009
This article helped me to develop Scribbly.
http://www.adobe.com/cfusion/marketplace/index.cfm?event=marketplace.offering&offeringid=15420&marketplaceid=1
Thanks,
- Jaswant Tak
Jan 13th, 2010
Thank this article.I have 1 question. Send mail automatic in only time.
EX: 10:30 AM
Jan 31st, 2010
Excellent tutorial. Thanks for the hard work.
Mar 2nd, 2010
perfect tut , thanx
Mar 21st, 2010
Is there a limit to the number of fields that you can create using this method?
Thanks for the info!
Apr 14th, 2010
I’m having the same issue that Suman and Alison above were having. I get the “thanks for submission” but no e-mail is sent. Any advice?
Apr 20th, 2010
Oh Thank you so much! Great examples! =D.
Have a great day!
Apr 28th, 2010
I tried out this example but it doesn’t send any email to my id….Do I need to configure anything other than importing the flex project?
May 5th, 2010
thx very nice
Jun 7th, 2010
[...] Create an email form in flex with php [...]
Jun 9th, 2010
hi friends,
This code is just ok…but still we have to make many changes indeed.
1) First…of all…
is not mapping the php/mail.php file for me.I tested it with an alert msg @ the top of php code.
2) Then the Php code have to set SMTP & also the sendmail_from in php.ini file.
You can do this by copy paste the below in the php code for setting the php.ini on the top of the page.
ini_set (“SMTP”,”mail.webmaster.com”);
ini_set (“sendmail_from”,”rajesh@webmaster.com”);
now the SMTP & sendmail_from is set.
3) The code simply shows the Alert.show(“Thank you for your submission “); from the result
after the submission of the form.No where the code generates a mail to the sendmail_from!!!
4) I have tried a code to check the mail() this is how it looks like…& it works perfectly…
<?php
ini_set ("SMTP","mail.webmaster.com");
ini_set ("sendmail_from","rajesh@webmaster.com");
$to = 'recipient@example.com';
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
if (mail($to, $subject, $body)) {
echo("Message successfully sent!”);
} else {
echo(“Message delivery failed…”);
}
?>
now all I got is to map the php file with HTTPService for passing the parameters to be mailed.
can anyone help with my code?
<?php
echo 'confirm(“Do you want this tuttu?”);’;
ini_set (“SMTP”,”mail.webmasterl.com”);
ini_set (“sendmail_from”,”rajesh@webmasterl.com”);
$senderName = $_POST['senderName'];
$senderEmail = $_POST['senderEmail'];
$subject = $_POST['emailSubject'];
$emailMessage = $_POST['emailMessage'];
$headers = “From: $senderEmail “;
$message = “From: $senderName, \nEmail Address: $senderEmail\nSubject: $subject\n\nMessage: $emailMessage”;
$message = stripslashes($message);
mail($headers,$subject, $message)
?>
Advance thanks…:)
Jun 15th, 2010
hi,
I finally found the code to get it works … I am attaching the code here hope it will be useful for all of you…
Note : The change is only in php code.& respective to the flex builder 3 complier.
1) The first thing is to get correct the php code as below
2) The compiler of Flex builder 3 have to be set to -use-network=false in the additional compiler args.
*purpose : For making the SWF file to map the php/mail.php file. If you don’t set this will show…
Error : Flex 2 Run-time error #2148: SWF file _ cannot access local resource
**also check up for SMTP, if you have entered everything correctly else will lead to..
Error : 550 Access denied – Invalid HELO name
It’s because you have improperly setup your smtp settings for outgoing mail.
Hope I helped you…
have a great day…:)
Jul 19th, 2010
Im wondering how u can add a verification image before sending that email?
Jul 31st, 2010
[...] Create an email form in flex with php [...]
Aug 13th, 2010
My contact forms will never be the same and I have wanted to work with flash for a long time now. This is a very good tutorial.
Thanks very much, Alpha
Aug 17th, 2010
yea just run the file on your wamp localhost and it should work
Aug 30th, 2010
[...] 30º Criando um formulário de email em Flex com PHP [...]
Sep 22nd, 2010
[...] Create an email form in flex with php: http://www.riacodes.com/flex/create-an-email-form-in-flex-with-php/ [...]
Sep 23rd, 2010
[...] Create an email form in flex with php: http://www.riacodes.com/flex/create-an-email-form-in-flex-with-php/ [...]
Oct 5th, 2010
hi i like what u have done,but can do the opposite i.e pass the parameter to the mxml file?
Dec 10th, 2010
Bonjour
Je viens de découvrir cet article, et je tenais à vous remercier de nous le faire partager.
Bonne continuation.
Dec 14th, 2010
Guys,
I tried the same code, but couldn’t receive any mail, any error message.
Can any one give me the complete working source.
I am using FLEX 3.
Jan 27th, 2011
really super tutorial
no words to decrib
Mar 29th, 2011
Hi,
I need something like, if I click the button a hbox will appear not aleart.
I am new in flex
Help me please !
Apr 8th, 2011
This was great. Very explanatory and straight to the good stuff. and Suvra:
you’d have to call a function to place the txt input to a label with an id of message.
textInput.errorString = evt.message;
evt.message could be a label id inside of an hbox. could appear(with alpha effects if you mean popup.)
this would pass the textInput to your evt.message label to show up on click.
whatever you want to display will come up once you set it to evt.message. Depends on if you want a validation event to show up.
hope this helps somewhat?
May 24th, 2011
Great tutorial! Its work great for me in builder 4. I tried this code in Flash Builder 4.5 for PHP and I get some errors. Whats changes I have to do to make it work in builder 4.5 for PHP? thanks!!!
Jun 17th, 2011
how can i get this to work inside an s application ?
Jul 2nd, 2011
where insert php file? inside exported files root dir, or inside a flex folder?
Jul 11th, 2011
where to write php file…? within the script tag of same mxml file or should i create a new file with php extension using WAMP server..??
Jul 13th, 2011
your code is not clear…i dnt understand where shud i put the php code…m tryin since morning
plzzz next time dnt forget to attech all the important information…..
Aug 25th, 2011
Hi I have used the code above but I am working in Flash Builder 4 (just trying to learn it as college student)
The mx code below will not work in 4 as MX compoent cant not be below a form.
error message show is:
Multiple markers at this line:
-HTTPService
-Parse error: ” is not allowed to follow ”.
I have code for a LogIn function using HTTP call as below and wondering is there any way to reuse the code or what would the code be to creat the new service call. Very new to all of this so all help , very very much appricated:)
protected function mysend():void
{
var _params:Object = new Object();
_params.userhandle = userhandleTextInput2.text;
_params.password = passwordTextInput2.text;
var _httpServiceName:HTTPService = new HTTPService();
_httpServiceName.url = “http://localhost/finalproject-debug/login.php”;
_httpServiceName.method = “POST”;
_httpServiceName.addEventListener(ResultEvent.RESULT, checkLogin);
_httpServiceName.send(_params);
}
Sep 1st, 2011
Looks awesome. I have integrated it my site and made some redesign. Thanks a lot.
Dec 16th, 2011
Thanks mate. Nice article.
Jan 13th, 2012
[...] 30º Criando um formulário de email em Flex com PHP [...]