You are currently viewing Send Email by Filling the HTML form using php Script

Send Email by Filling the HTML form using php Script

Here First you know how your mail script will work, its the first and simple script,

<?php $to = "[email protected]"; $subject = "Hi!"; $body = "Hi,\n\nHow are you?"; if (mail($to, $subject, $body)) { echo("Message successfully sent!"); } else { echo("Message delivery failed..."); } ?>

the 3 variables $to, $subject, and $body are the variables that used to send email using php script, here you may add an additional header like from or CC or BCC, etc. but these are optional, mail is the php predefined keyword.

Detailed with Form
First of all, you will define a form and handle it with the CSS as you would like to.
make a form of how many fields you would like to create depends on your needs.

<form method="post" action="contact.php">
<select name="sendto"><option value="[email protected]">General</option><option value="[email protected]">Support</option><option value="[email protected]">Sales</option></select><br>
<label>Name:</label><input size="25" name="Name"><br>
<label>E-mail:</label><input size="25" name="Email"><br>
<label>Company:</label><input size="25" name="Company"><br>
<label>Phone:</label><input size="25" name="Phone"><br>
<label>Massage:</label><br>
<textarea name="Message" rows="5" cols="35"></textarea><br>
<input type="submit" name="send" value="Submit"><br>
</form>

here you complete your form
Now, let us go to some php script.

<?php $to = $_REQUEST['sendto'] ; $from = $_REQUEST['Email'] ; $name = $_REQUEST['Name'] ; $headers = "From: $from"; $subject = "Web Contact Data"; $fields = array(); $fields{"Name"} = "Name"; $fields{"Company"} = "Company"; $fields{"Email"} = "Email"; $fields{"Phone"} = "Phone"; $fields{"Message"} = "Message"; $body = "We have received the following information:\n\n"; foreach($fields as $a => $b)
{ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

$headers2 = "From: [email protected]";
$subject2 = "Thank you for contacting us";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.xyz.com";

if($from == '') {print "You have not entered an email, please go back and try again";}
else {
if($name == '') {print "You have not entered a name, please go back and try again";}
else {
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $autoreply, $headers2);
if($send)
{header( "Location: http://www.xyz.com/thankyou.html" );}
else
{print "We encountered an error sending your mail, please notify [email protected]"; }
}
}
?>

this is the code to send an e-mail. hope you learn from it.