mail()

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:
  1. mail($to, $subject, $message, $headers);

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

PHP:
  1. 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:
  1. if(mail($to,$subject,$message,$headers)){
  2. echo "Email Sent";
  3. }else{
  4. echo "Email Sending Failed";
  5. }

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:
  1. $to="someeila@comapny.com";
  2. $from=$_POST['email'];
  3. $message="my message";
  4. $subject="Subject of message";
  5. $headers = "From: $from";
  6. if(mail($to,$subject,$message,$headers)){
  7. echo "Email Sent messaage";
  8. }else{
  9. echo "Email Sending Failed mesasage";
  10. }

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:
  1. if(!isset($submit)){
  2. <form action="$_SERVER[PHP_SELF]" method="post">Name:
  3. <input name="name" type="text" />
  4. Email:
  5. <input name="email" type="text" />
  6. Message:
  7. <textarea cols="40" rows="15" name="message"></textarea>
  8. <input name="submit" type="submit" value="send" /> </form>";
  9. }else{
  10. $to="asmgomaa@gmail.com";
  11. $from=$_POST['email'];
  12. $message=$_POST['message'];
  13. $subject="Website Contact Form";
  14. $submit=$_POST['submit'];
  15. $headers = "From: $from";
  16. if(mail($to,$subject,$message,$headers)){
  17. echo "Email Sent";
  18. }else{
  19. echo "Email Sending Failed";
  20. }
  21. }
  22. ?&gt;

An example of it is available here .

I hope this is helpful and makes the mail() function clear and easier to use.

VN:F [1.9.3_1094]
Rating: 4.0/10 (1 vote cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)
mail(), 4.0 out of 10 based on 1 rating
Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists

Leave a Reply