PHP Echo Tutorials

Email with PHP

Written by phpecho.com   

In this tutorial we discuss how we can use the email capability of PHP. Sending emails using PHP is simple and takes only a few lines of code. What you must take care is to ensure that you use this for the right purpose. For example, it is pertinent that you keep your server capability in mind while sending mails using PHP. The ideal use would be where you need to send a confirmation mail to the user after an operation is performed. Okay, so let us get started right away. First we show a piece of code which can be used to send a simple email. The code snippet is below – the explanation follows.

<?php
   //the to email address
   $to = '
  This e-mail address is being protected from spambots. You need JavaScript enabled to view it
 ';
   //the subject of the email
   $subject = 'Test Email Using PHP'; 
   //the actual message 
   $message = "Hello World!\n\nThis mail is sent using PHP."; 
   //other headers 
   $headers = "From: 
  This e-mail address is being protected from spambots. You need JavaScript enabled to view it
 \r\nReply-To:  
  This e-mail address is being protected from spambots. You need JavaScript enabled to view it
 ";
   //sending the email
   $mail_sent = @mail( $to, $subject, $message,  $headers );
   //status message 
   echo $mail_sent ? "Mail sent" : "Mail failed";
   ?>

The most critical line in this code snippet is the @mail command line. This function does the actual work of sending a mail. For it to work correctly, it needs to know a few things. The email address where the mail has to be sent , the subject and the actual body of the message are needed by this function. In our example, those have been passed to the @mail function. In addition there could be additional information that we may want to pass. These would normally include the ‘from address’ and the address where replies should be sent. This is added in the headers.

Note that in case you want to have multiple lines in the body of the mail, you will need to separate them using \n characters as line breaks. Multiple information in the headers also need to be separated using \r\n. In case you want the email to be sent to multiple recipients, then add their names to the $to variable separating them by commas. One final observation: the mail function returns a Boolean value based on which you will know if the mail was sent successfully. As you would now realise, sending an email using PHP is very simple – a matter of only one function!