mail ($to, $subject, $message, $headers, $additional_parameters);
So if we wanted to send an email to the address 'bob@boodle.com', with a subject of 'Hello' and a message of 'Howdy, bob' then we would write the following:
mail('bob@boodle.com', 'Hello', 'Howdy, Bob'); When sending emails with PHP, you must use a From: header. This can be set in the headers parameter. So if we wanted to adjust the above example to have a From header, we would change it to this:
mail('bob@boodle.com', 'Hello', 'Howdy, Bob', 'From:email@address.com'); With all that in mind, here is a contact script which uses the mail function to send an email to your email address.
The user enters their name, email address and message into a form and when the user submits the form the mail is sent to your address. Here it is, fully commented:
<?php
session_start();
#ENTER THE EMAIL ADDRESS WHICH THE EMAIL WILL BE SENT TO
$myEmail = 'your@email.com';
if(isset($_POST['submitted'])){ //If the user submitted the form
$errors = array(); //Initialises errors array
#FORM VALIDATION BELOW
if(empty($_POST['email'])){
$errors[] = 'Please enter an email address';
}else{
$email = stripslashes($_POST['email']);
}
if(empty($_POST['subject'])){
$errors[] = 'Please enter a subject';
}else{
$subject = stripslashes($_POST['subject']);
}
if(empty($_POST['msg']) || $_POST['msg'] == 'Msg here'){
$errors[] = 'Please fill in a message';
}else{
$msg = stripslashes(htmlentities($_POST['msg']));
}
#IF THERE IS NO ERRORS, SEND THE MAIL
if(empty($errors)){
mail($myEmail, $subject, $msg, 'From:' . $email);
$thanks = 'Thankyou for your email.<br />';
}
}
echo $thanks;
#DISPLAYS THE ERRORS
if(!empty($errors)){
echo'<h4>Error!</h4>';
foreach($errors as $meg){
echo'<br />' . $meg;
}
echo'<br />';
}
#STICKY FORM
if(isset($_POST['submitted'])){
$sub = $_POST['subject'];
$em = $_POST['email'];
$mess = $_POST['msg'];
}
else{
$sub = NULL;
$em = NULL;
$mess = 'Msg here';
}
//THE FORM BELOW
echo'<br /><form method="post" action="' . $_SERVER['PHP_SELF'] . '">
<label>Subject (required)</label><input type="text" name="subject" value="' . $sub . '" /><br />
<label>Your email (required)</label><input type="text" name="email" value="' . $em . '" /><br />
<textarea name="msg" rows="8" cols="30">' . $mess . '</textarea><br />
<input type="submit" name="submit" value="Send" />
<input type="hidden" name="submitted" value="TRUE" />
</form>';
?> The form that is displayed is a very basic form, so feel free to edit the script to match your needs.
Thanks for reading!
discuss this topic to forum
