Top Good Web Design

Web Designer

PHP for Beginners: Part 3 – Email with PHP

Today We are continuing our PHP series. One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. In this part I will show you how to send e-mail messages using PHP.

For those who missed the previous parts:

Part 1

Part 2


PHP mail() function

E-mails in PHP can be easily sent using the library function ‘mail’. This function takes four arguments to send E-mails from a PHP web page and returns ‘true’ upon successful delivery of Email. The parameters of this function are as follows:

  • Recipient E-mail address
  • E-mail Subject
  • E-mail message (body)
  • Headers and additional parameters


mail( string to, string subject, string message [, string additional_headers [, string additional_parameters]] );

The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an e-mail ( Sender E-mail address ) but you can also include other headers like cc and bcc.

This function returns the boolean value ‘True’ if the mail is sent successfully, otherwise it returns ‘False’.

Sending An E-mail

Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message:

$to = "";
$subject = "PHP Rock";
$body = "PHP is one of the best scripting languages around";
$headers = "From:\n";
echo "Mail successfully sent to $to";

This code will actually do two things. Firstly it will send a message to with the subject ‘PHP Rock’ and the text:
PHP is one of the best scripting languages around
and the e-mail will be from It will also output the text:
Mail successfully sent to
to the browser.

Formatting E-mail

Something you may have noticed from the example is that the From line ended with \n. This is actually a very important character when sending e-mail. It is the new line character and tells PHP to take a new line in an e-mail. It is very important that this is put in after each header you add so that your e-mail will follow the international standards and will be delivered.

The \n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.

PHP Validate Email

PHP validate email script is an easy way to validate an email address. Use this quick and simple PHP regular expression for email validation. This is also case-insensitive, so it will treat all characters as lower case. It is a really easy way to check the syntax and format of an email address. Function will return TRUE if address is valid and FALSE if not.

function isValidEmail($email){
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);

Mail Without Variables

The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could also have been done on one line using text like this:

mail("","PHP Rock","PHP is one of the best scripting languages around","From:\n");

But that would make your code slightly harder to read.

Error Control

As anyone who has been scripting for a while will know, it is extremely easy to make mistakes in your code and it is also very easy to input an invalid e-mail address (especially if you are using your script for form to mail). Because of this, you can add in a small piece of code which will check if the e-mail is sent:

if(mail($to,$subject,$body,$headers)) {
echo "An e-mail was sent to $to with the subject: $subject";
} else {
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid";

This code is quite self explanatory. If the mail is sent successfully it will output a message to the browser telling the user, if not, it will display an error message with some suggestions for correcting the problem.

BONUS: Sending Email Using the Zend Framework

In addition to my previous Zend Framework tutorials, in this section i will introduce you another cool feature of that amazing framework, working with emails.

The Zend Framework’s Zend_Mail component, when coupled with the Zend Framework’s approach to minimizing redundancy and maximizing portability, offers the ideal solution for configuring and transmitting email through PHP-driven webpages. In this section, we will be using the Zend_Mail component.

First, within the application’s config.ini file, I define various parameters used to configure the transmission solution:

; email

email.smtpserver =
email.username   =
email.password   = strong_password    =

Within the bootstrap.php file, I configure Zend_Mail’s transport mechanism, drawing upon the parameters defined in config.ini:

$mailConfigs = array('auth' => 'login',
'username' => $config->email->username,
'password' => $config->email->password,
'ssl' => 'tls');

$tr = new Zend_Mail_Transport_Smtp($config->email->smtpserver,

Although this executes with each request, the overhead required to do so is minimal and will not affect performance. Finally, I invoke code similar to the following from within the appropriate controllers:

try {
// Create a new mail object
$mail = new Zend_Mail();

$mail->setSubject("Your account has been created");

$email = "Thank you for registering!";


$this->view->success = 1;
} catch (Exception $e) {
$this->view->errors[] = "We were unable to send your
confirmation email. Please contact

If you’d like to add an attachment, all you need to do is invoke the $mail object’s createAttachment() method:


If you want to send HTML-formatted email, just use the setBodyHtml() method instead of setBodyText():

$mail->sendBodyHTML("Thank <b>you</b> for registering!");

Additional Resources

Sending email from your PHP-powered websites is easy once you’ve been provided with the necessary background, so hopefully this tutorial helped alleviate any initial confusion you had in this regard. For further information, check out the following resources for more information about sending email using PHP:

What’s Next?

In part 4 I will continue covering mail by showing you how to build a simple form to mail program in PHP. And will tell you some final notes 🙂 So, see you in next part.

Leave a Reply