Tuesday, 25 October 2011

Make mail() In PHP simple Tutorial

http://3.bp.blogspot.com/-ujGdQBt1rMM/TqeYgwqWJDI/AAAAAAAAAnk/FlPfxYun7l0/s1600/php.gif
A famous function, yet mis-used is mail().
Mail function can be used in several ways, eg a contact form and auto-senders suitable for confirming registration.
Ok the function is used like this:

PHP:

mail($to, $subject, $message, $headers);



you can either set the variables or enter them manually like this:

PHP:
 
 mail(myemail@mycompany.com, message subject, message , headers);


Although its preferred to use variables because its easier to use and modify later.
To make sure the message was sent correctly you can use the following "if block"

 
 PHP:

if(mail($to,$subject,$message,$headers)){
echo "Email Sent";
}else{
echo "Email Sending Failed";
}


If you are making an auto-sender you add this to the page that has the email address passed in most probably by a form, so you do this:

PHP:

$to="someeila@comapny.com";
$from=$_POST['email'];
$message="my message";
$subject="Subject of message";
$headers = "From: $from";
if(mail($to,$subject,$message,$headers)){
echo "Email Sent messaage";
}else{
echo "Email Sending Failed mesasage";
}

The other example i mentioned at the beginning was the contact form, look at this form, it has both parts in one PHP page:

PHP:

if(!isset($submit)){
echo "
<form action="$_SERVER[PHP_SELF]" method="post">Name:
<input name="name" type="text" />
Email:
<input name="email" type="text" />
Message:
<textarea cols="40" rows="15" name="message"></textarea>
<input name="submit" type="submit" value="send" /> </form>";
}else{
$to="asmgomaa@gmail.com";
$from=$_POST['email'];
$message=$_POST['message'];
$subject="Website Contact Form";
$submit=$_POST['submit'];
$headers = "From: $from";
if(mail($to,$subject,$message,$headers)){
echo "Email Sent";
}else{
echo "Email Sending Failed";
}
}
?> 

0 comments:

Post a Comment