WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search


Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
פרייסז - השוואת מחירים בסופר
ZeroLag.com
Texas Holdem Poker Evangelists

Go Back Add a Comment Send this Article to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES SUBMIT AN ARTICLE PRINT
Title : Sending Form Data in EMail
Categories : PHP, Email, HTML and PHP Picture not available
Meloni Julie
Date : 2000-01-01
Grade : 5 of 5 (graded 2 times)
Viewed : 68622
Search : More Articles by Meloni Julie
Action : Grade This Article
Tools : My Favotite Articles


Submit your own code examples 
 


Using PHP to send the contents of a form to a specified e-mail address is so easy that you'll wonder why people don't do it every day. The PHP mail() function takes four arguments: the recipient, the subject, the message and any additional mail headers. In this short tutorial, you'll learn to set values for each of these variables, then send off the mail and return a confirmation page. We'll use a two-step process; one file for the form and one file for the PHP code to process the form, send the mail, and return a response. A note: this tutorial uses the PHP file extension ".php3" in its examples. If you use a different file extension to indicate PHP files, such as ".phtml" or ".php", please substitute accordingly.



First, start your favorite editor and create the HTML form. Personally, I adopted the "show/do" method when creating multi-step applications: if a file has the "show_" prefix, it's usually a form, and if it has the "do_" prefix, it's usually the PHP code. So, create a file called "show_form.html", containing two text fields and a textarea, like so:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>E-Mail Form&lt;/TITLE>
&lt;/HEAD>
<BODY>

<FORM method="POST" action="do_sendform.php3">

<P>Your Name:<br>
<INPUT type="text" name="sender_name" size=30>
&lt;/p>

<P>Your E-Mail Address:<br>
<INPUT type="text" name="sender_email" size=30>
&lt;/p>

<P>Message:<br>
<textarea name="message" cols=30 rows=5>&lt;/textarea>
&lt;/p>

<INPUT type="submit" value="Send This Form">

&lt;/FORM>

&lt;/BODY>
&lt;/HTML>


Let's take apart this example form and see just what I've told you to do. First, the form action is "do_sendform.php3". This is the name of the file that you will create in just a little bit, which will contain the code to process the form and send the e-mail. Next, we have two input fields and a textarea. By default, the NAME of an input element becomes the name of the variable passed to "do_sendform.php3". So, when the form is sent, we will be passing three variables to "do_sendform.php3": $sender_name, $sender_email and $message. In this tutorial, you'll be sending the form to yourself with a specified subject, so both the recipient e-mail address and the subject will be coded into your PHP script.





Simple enough so far? Ok, let's tackle the PHP code. Go ahead and create the file "do_sendform.php3" in your text editor of choice. Start the script with this piece of code:


<?php_track_vars?>


If you aren't in control of your server or you don't know if variable tracking is turned on, adding this line will ensure that at least for this script, variable tracking is enabled.



Next, build the e-mail by concatenating strings to form one long message string. "Concatenating" is a fancy geek word for "smashing together". You'll use the newline (\n) and tab (\t) characters to add spacing where appropriate. Continue your PHP code by adding this snippet:


<?php

$msg
= "Sender Name:\t$sender_name\n";


In this line, you are beginning the message string by creating a variable called $msg and adding to it the text "Sender Name", followed by a tab, followed by the value of $sender_name and a newline character. When this script is executed, the variable $sender_name will be replaced by the text entered in the form.



Continue creating the message string by adding display text for the remaining text values to the variable $msg. Note the use of the concatenation operator (.=) when adding to the variable $msg:


$msg .= "Sender E-Mail:\t$sender_email\n";
$msg .= "Message:\t$message\n\n";


The final line contains two newline characters, to add additional whitespace at the end of the string. At this point, all you've told PHP to do is to build a very long string, like so:


$msg = "Sender Name:\t$sender_name\nSender E-Mail:\t$sender_email\nMessage:\t$messsage\n\n";


However, using the concatenation operator and separating your code with whitespace certainly makes it easier to edit later, as you won't have to search through one long line of text in order to make a change! Remember, whitespace is your friend...and will make you popular with any coding buddies who may have to edit your stuff.



At the beginning of this tutorial, I told you that the mail() function takes four arguments: the recipient, the subject, the message and any additional mail headers. In your code, now create variables to hold the values that you control - recipient, subject and mail headers:


$recipient = "[email protected]";
$subject = "Web Site Feedback";


Obviously, use your own e-mail address and any subject you want. Next, create a variable for additional mail headers. Some basic mail headers are "From" and "Reply-To". Create a variable called $mailheaders and add the following to it:


$mailheaders = "From: My Web Site <> \n";
$mailheaders .= "Reply-To: $sender_email\n\n";





Use "<>" in the "From" header to indicate a blank e-mail address. Alternately, you could place the variable $sender_name in the "From" header as well as in the "Reply-To" header, but if the user has not completed that field, the form may not make it through your mail server with a blank "From" header. Best just to fill it with something generic, and use the "Reply-To" header for the sender's e-mail address.



You now have all of the pieces that the mail() function needs in order to, well, function. Place it in your code:


mail($recipient, $subject, $msg, $mailheaders);


Finally, you should return something to the user's screen so they know the form has been sent. Otherwise, you know _someone_ is going to sit there and press the "Send This Form" button about a billion times, thereby flooding your mailbox and making you curse a lot. So, add a couple of lines of simple HTML code and end your PHP code:


echo "<HTML><HEAD><TITLE>Form Sent!&lt;/TITLE>&lt;/HEAD><BODY>";
echo "<H1 align=center>Thank You, $sender_name&lt;/H1>";
echo "<P align=center>Your feedback has been sent.&lt;/P>";
echo "&lt;/BODY>&lt;/HTML>";

?>


Use the variable $sender_name in the content that is returned to the user's screen, as some semblance of "custom" content. Or, maybe it's just politeness. In any event, make a user feel loved and they'll come back to your site.



Your entire PHP script should look something like this:


<?php

$msg
= "Sender Name:\t$sender_name\n";
$msg .= "Sender E-Mail:\t$sender_email\n";
$msg .= "Message:\t$message\n\n";

$recipient = "[email protected]";
$subject = "Web Site Feedback";


$mailheaders = "From: My Web Site <> \n";
$mailheaders .= "Reply-To: $sender_email\n\n";

mail($recipient, $subject, $msg, $mailheaders);

echo
"<HTML><HEAD><TITLE>Form Sent!&lt;/TITLE>&lt;/HEAD><BODY>";
echo
"<H1 align=center>Thank You, $sender_name&lt;/H1>";
echo
"<P align=center>Your feedback has been sent.&lt;/P>";
echo
"&lt;/BODY>&lt;/HTML>";

?>


Of course, feel free to substitute label names, spacing and any other items specific to your environment. As always, to learn more than just the basics, learn the PHP Manual and read the PHP Mailing List Archives!









Managing a Simple Mailing List
Categories : PHP, MySQL, Email
How To add paging (Pagination) with PHP and MySQL
Categories : PHP, Beginner Guides, Databases, MySQL, HTML and PHP
Making PHP Forms Object-Oriented
Categories : PHP, HTML and PHP, Object Oriented
Webstatistics with Redirectors
Categories : PHP, HTML, HTML and PHP
Uploading files to the server with PHP
Categories : PHP, File System, HTML and PHP, HTTP
Alternating row colors with PHP and mySQL
Categories : PHP, Databases, MySQL, HTML and PHP
tracking where and what on your site people are clicking
Categories : PHP, MySQL, HTML and PHP, HTML
Multicolumn Output from a Database with PHP
Categories : PHP, Databases, HTML and PHP, MySQL
Static HTML Generation With PHP
Categories : PHP, HTML and PHP
Create Your Own Mail Script With PHP and IMAP
Categories : IMAP, Email, PHP
Converting XML Into a PHP Data Structure
Categories : PHP, XML
Installing Apache Web Server and PHP 4 on Linux
Categories : PHP, Web Browsers, Apache, Linux
User Authentication With patUser (part 2)
Categories : PHP, Authentication, Security
Simple Connection to mSQL with PHP
Categories : PHP, mSQL, Databases
Working with Permissions in PHP, Part 1
Categories : PHP, Security
Anonymous wrote : 1
It would be great if this sample included form
validation. Most of the time, samples have either or,
which is not helpful in realworld solutions. Other than
that, I think it`s pretty neat for beginners.
Rafi Ton wrote : 2
Here is a small modification of the php script that
performs a simple form validation. The new script just
checks whether the user entered an email address and
a message body.

<?php

if ($sender_email and $message)

{

$msg = "Sender Name:\t$sender_name\n";
$msg .= "Sender E-Mail:\t$sender_email\n";
$msg .= "Message:\t$message\n\n";

$recipient = "[email protected]";
$subject = "Web Site Feedback";


$mailheaders = "From: My Web Site <> \n";
$mailheaders .= "Reply-To: $sender_email\n\n";

mail($recipient, $subject, $msg, $mailheaders);

echo "<HTML><HEAD><TITLE>Form Sent!
</TITLE></HEAD><BODY>";
echo "<H1 align=center>Thank You,
$sender_name</H1>";
echo "<P align=center>Your feedback has been
sent.</P>";
echo "</BODY></HTML>";

} else {

echo "<HTML><HEAD><TITLE>Form empty!
</TITLE></HEAD><BODY>";
echo "<H1 align=center>There is no email address or
no message boby.</H1>";
echo "<P align=center>Please go back and make sure
you have entered an email address and a message
body</P>";
echo "</BODY></HTML>";

}

?>
gabriel leung wrote : 10
Is it possible to send attachment?
Anonymous wrote : 18
how to send an html embedded message i mean can i sned a
message through which i can link to other sites.
Boaz Yahav wrote : 19
You can see an example of sending attachments here :

http://www.weberdev.com/index.php3?
GoTo=get_example.php3?count=1583
dhaval desai wrote : 22
Hi!
I tried to send the form, but I get an error message.
It says "Warning failed to connect on line 18."
Allthought I have pphp windows send mail support.
Can anybody help me please.

Dhaval Desai
Anonymous wrote : 29
I am using a combo of the email form processing
and the email file attachment scripts to allow my
visitors to send me a copy of the `current cam pic`
that is displaying on my webcam. It is working just
fine as long as the pic I want to send is sitting right
there on the same server as the php script. But...I
was wondering if there is a way to have it send a file
that is sitting on a different server? I tried just
using the URL to grab it...but it is taking out the /`s
from the URL, thus making it unusable (also seems
to be turning it into a link attachment instead of an
actual file attachment). Does this make any
sense? Is there any way to fix it?
Candi
Anonymous wrote : 44
The code seems working fine but somehow i was not
able to receive mail. No error, thanks section is working
fine with the user greeting. But i was not able to receive
form data as mail.
I wonder why?
Anonymous wrote : 45
Your script works just fine, but i`m wondering about
recieving email. How do you retrieve emails from a pop3
server?
Anonymous wrote : 66
I tried the script and it worked like a link to another
page instead of sending
BiTDaemon wrote : 84
to veryfy if the from was completely filled up can be
done via javascript like: <br>
if (formName.formField.value.length < 1) {
// then the field has no value
...
alert(`Field required missing ...");
formName.formField.focus();
}
<br>
or via PHP: <br>

if ((trim($FieldVar) || trim($FieldVar)) == "" || " ") {
printf "Error message here ... ";
}
Raymond Sabee wrote : 104
Hi there,

I just wanted to say that is works perfect!
And thanks for the validation check in an other comment.

Keep up the good work!

Greetz Raymond Sabee
Webdesigner/webdeveloper/webmaster Wegener NV
Marcelo Muzilli wrote : 113
Why my code doesn`t work properly? It shows me the
following message:

Warning: Failed to Connect in d:\program files\apache
group\apache\htdocs\do_sendform.php on line 25

This line is about the mail() function. What I need to do?
Anonymous wrote : 118
great
i`d like to send my data with a form and send them in
html format. how to write it in a simple way?
with mime? ...
thank you for your response ;-)
Anonymous wrote : 123

I have used this code here and found it really working !!
Bart Elen wrote : 127
Same here. The code works perfectly, thanks for
sharing, but me too, i can`t seem to receive any e-mail.
Would it be possible to use a localhost command or so?
Can anyone help me out over here?
Anonymous wrote : 181
It`s not so hard to get Mail() to work.
Find the php.ini file on your`e hd.
it`s ussually in the Root of Apache or Windows
In de ini file find the folowing line:
[mail function]
SMTP = You`re smtphost
;for win32 only
sendmail_from = [email protected] ;for
win32 only

Change the `You`re smtphost to the one you use to
send mail with.

You can find that in you`re outlook settings

Grtz Smokey
Anonymous wrote : 182
/* If you want to send html mail, uncomment the
following line */
// $headers .= "Content-Type: text/html; charset=iso-
8859-1\n"; // Mime type

(from the PHP manual)
Anonymous wrote : 183
I`m trying to use this script, but it keeps hanging
my system.

I have modified it slightly, but it still hangs my
system.

Can someone help me figure out what`s wrong?

Any help would be appreciated.

Anonymous wrote : 194
I am trying to do something a little more complex. I have an extremely long
survey form which is broken into 20 long forms. I want to insert into my
database all of the data in $HTTP_POST_VARS but since it is an array it will
not take a straight forward insert table_name set
variable=$HTTP_POST_VARS; If anyone has some insight into this please
e-mail me! thanks!
Anonymous wrote : 216
hi there!

It`s a really nice script!

Please let me know how to modify it to send a cc and
bcc.
Davy Jong wrote : 219
Thanx for the script. I`m searching for a FORM to EMAIL
php-script. The goal is to attach a file, (like a local
WORD-document on the client-PC) via a upload-button
on the form, to an e-mail.

Does someone have a examplescript of this?
Anonymous wrote : 225
Great Script.....I`m new to PHP and I had same problem
with not receiving any e-mails.

I have PHP hosted on my ISP`s server, I eventually
found their information and have to use the following to
work.

Note how I had to amend the Mail() line for this to
work....

mail($recipient, $subject, $msg, "From:
[email protected]");

Anonymous wrote : 237
I like the script and it works on my local apache install,
but my host disabled mail() :(
Anonymous wrote : 246
Great!
But I`d like to add attachment file to my email.
How should I do this?
Do not tell me please it is simple too, because it is not
for me. OK?
Heeelp me !!!!!
Anonymous wrote : 251
i appreciate this script very much, but i dont know why
after i customised the recipient and upload to my server
and i gave it a try it didn`t work. i uploaded it to
http://miaowa.uhome.net/show_form.html , after i
clicked submit, it responds and shows sent msg but i
got no mail at all. pls help, it`s quit urgent. thanks a lot.
Anonymous wrote : 256
The script works fine. I want to figure out how to add a
Cc: & Bcc: to the email though. How could this be done?
Matt Ellis wrote : 272
To include cc & bcc: insert into the html form:

CC: <INPUT type="text" name="cc" size=30>
BCC: <INPUT type="text" name="bcc" size=30>

then in the php script:
$mailheaders .= "CC: $cc\n";
$mailheaders .= "BCC: $bcc\n";

(these lines go after the inital $mailheaders line and
before the mail(... line


Now I`ve got a question:
In the body of a message sent using this form, whenver
a ` or a " is used, a slash is inserted before it (ie this: `
becomes this: \` )

Is there any way to stop this happening?

It`s not just annoying, but it means I can`t add an
attachment function as in the same way, the path of
attachments gets turned into eg:
C:\\My Documents\\suff\\attachment.gif

Thanks
Anonymous wrote : 275
i had tried that earlier and saw that the cc: field
appeared in the original mail, but the cc address
does not receive a copy of it.
luca corleone wrote : 277
i like it it cool but very difficult to me!!!
luca wrote : 278
i like it it cool but very difficult to me!!!
Anonymous wrote : 286
Hi ,
This scrip is great. When i am trying to use this it gives a
warning like this:
Warning: Unknown error in
c:\inetpub\wwwroot\myweb\do_sendform.php on line 15
Finally it did send the message ,
Thank You, ila
Your feedback has been sent.

but i did not recieve any mail in my account.

Your suggestion will help me .Thanx in advance.

--Ila


harsha n wrote : 300
wow this is amazing and i have a question

it possible to send attachment through this email
script. but how?

please clarify it
Roger Tannous wrote : 307
Hi,

thanks for this useful tutorial;

But I`m experiencing a problem:
I have a form with input fields, selects,...
can i retrieve form values into php variables in the
same page before submitting?
I know i can do it with javascript, but i don`t know how
to pass this value to a php variable before submitting
the document.

Can you help please?
Thanks in advance.
Roger= "Thinking Motorola";
Roger Tannous wrote : 308
Ok, i will reply to myself as i found the answer!!

No, one cannot retrieve the value of a form input before
he submits the document... because PHP is a server-
side script/language.

So, i made the page call itself (this was specified in the
action of the form).
So, inside the page, there are multiple controls of which
variable is set,.... and multiple JavaScript functions.
Finally, when all the data are ready, the page submits
to another page.
This is done by changing the action attribute for the
form like this:
document.all.Form_Name.action="./resconf.php";

then:
document.all.Form_Name.submit();


This is what it`s all about.


Best Regards,
Roger ="Thinking Motorola";
gerry brown wrote : 312
Hi,

I am a complete novice, trying to retrieve email
addresses from a MySQL database using PHP. I need
the email address inserted as a simple variable in a
form, such as

<input type="hidden" name="venue_email" value="<?
mysql_connect("localhost", "username", "password");
$result1 = mysql(database,"SELECT * FROM table
WHERE autono = `$autono`");
$num = mysql_numrows($result1);
$i = 0;
while($i < $num) {
echo mysql_result($result1,$i,"EmailName");
$i++;}
?>">

Believe it or not it seems that I did something right,
and the email address actually appears in the resultant
HTML page, e.g.

<input type="hidden" name="venue_email"
value="[email protected]">

However I then need to be able to have the form
results emailed to this address. In my very limited
knowledge I tried putting a field like the others in the
HTML, such as:

Email: [venue_email]

into the text document to be emailed. However,
needless to say it didn`t work. Have you any advice that
you can offer to a complete novice trying to find his
way? Plain English please...pretend that I am not really
a coder. You wouldn`t be far wrong.
Kelvin Poon wrote : 366
This is great, thanks for sharing.

I was wondering, could we edit the format of the message?
For example if I want my font to be Arial or if I want my font to
be bold, underlined or a different colour. Could we do that?

Thanks.
Kelvin
George C. wrote : 372
The script is pretty basic, its the explaining of its functionality
and of code thats nice, for newbies like me. Thank you for that,
saved me some days of work.

Now. On to my little problem.

My host requires that you use pop3 auth before sending emails
via smtp, and that kinda defeats the point of this script.

Would there be anyway for me to go around this ? Maybe
include pop3 auth in the php script, so its done automatically ? I
imagine that would mean defining user/pass for pop3 in the php
itself. Not very secure, I imagine, but I haven`t got any other
solutions that I can think of.

Thanks in advance, and sorry for the long post :)
jard secret wrote : 388
your code is very nice for the php beginner easy to understand

it is possible to receive the recipient arabic text, how can we
do for that code
Anwarul Kabir wrote : 404
nice script. I have followed your code and created mine with
the attachment function and also a formatted email in HTML.
I have a question to you. My users will be putting their SSN in
the form. Since i had no previous PHP knowledge i am
wondering if you can tell me if the php form page is secure or i
need to write some special code to make it secure. My website
is hosted in a 3rd party server and they said they have
configured php stuff like .ini file and other things the way it
should be for more security but I was wondering if i need to do
anything on my part?
thanks