Create an email form in flex with php

May 6th, 2009 in Flex

The following code demonstrates how to build an email form that supports some validation and that send the email by using a php script.

View DemoDownload Source

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;
}
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Twitter


What you think ...

(22 Comments)

+ Add a Comment
  1. jaswant tak
    Jun 2nd, 2009

    Very nice article, It helped me for my application. Thanks mate.

  2. Oktigh
    Jun 7th, 2009

    thanks very nice :)

  3. Steve
    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.

  4. Pierre
    Aug 4th, 2009

    Thanks a lot! Great code, implements fast, no errors. This is fast & furious.

  5. Chris
    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.

  6. suman
    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

  7. Diagne
    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.

  8. Steve
    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

  9. Twitter Trackbacks for Create an email form in flex with php | RiaCodes [riacodes.com] on Topsy.com
    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 [...]

  10. Brooks
    Sep 2nd, 2009

    Great stuff…

  11. Henry Lawson
    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!

  12. Alison
    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.

  13. Tom
    Sep 22nd, 2009

    Thankx u saved me lot of time
    Works great

  14. Chris
    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

  15. 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

  16. 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

  17. jack
    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.

  18. Chris
    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.

  19. Chris
    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

  20. jaswant tak
    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

  21. Trung Hieu
    Jan 13th, 2010

    Thank this article.I have 1 question. Send mail automatic in only time.
    EX: 10:30 AM

  22. J.F. Herrera
    Jan 31st, 2010

    Excellent tutorial. Thanks for the hard work.

Leave a Comment

Name (required)

E-mail (required, will not be published)

Website