http://www.developer.com/

Back to article

Sending Email with PHP


November 5, 2008

Email plays a crucial role in website development, whether you'd like to confirm a new registrant's email address, recover a lost password, or provide prospective clients with a convenient means to contact you. But, although languages such as PHP come packaged with the ability to send email (in PHP's case, using the aptly named mail() function), sending email successfully through a web page isn't always as simple as it may seem. In this tutorial, I'll introduce you to several solutions for sending email using PHP, including PHP's native mail() function, PEAR's Mail package, and the Zend Framework.

Email and PHP: The Fundamentals

Most newcomers to PHP were initially attracted to the language due to its low barrier of entry. After all, adding dynamic data to a web page by using PHP (the current date, for instance) can be done with as little as one line of code. Along these lines, one of PHP's common selling points is in fact its mail() function. What's not to like about a language that can send email via a single simple function? But, the reality is there's a bit more involved when it comes to successfully sending email in this fashion, particularly when it comes to doing so on a platform-specific basis.

On the Linux- and Unix-based platforms, PHP's mail() function will send email through Sendmail, the open source mail transfer software responsible for sending as much as 75% of the world's email. Because Sendmail is typically installed by default on Linux- and Unix-based servers, chances are the mail() function is going to work out of the box.

On the Windows operating system, the process is a tad more involved. Because Windows doesn't come with a mail transfer service installed, the mail() function must instead rely on a third-party email server, as defined by PHP's SMTP configuration directive. When mail() is called, PHP will contact this SMTP server and attempt to transmit the email using it.

PHP's Mail-Specific Configuration Directives

The aforementioned SMTP directive is just one of five supported by PHP:

  • SMTP: Defines the SMTP server to use when sending email through PHP scripts running on the Windows operating system.
  • smtp_port: Defines the SMTP port to use when connecting to the SMTP server defined by the SMTP directive. The default is 25.
  • sendmail_from: Identifies the sender of email sent through PHP scripts running on the Windows operating system. If you want to use multiple originating addresses, you'll soon learn how to override this directive from within the mail() function.
  • sendmail_path: This Linux/Unix-specific directive allows you to define the path to your Sendmail program if does not reside within your system's path.
  • mail.force_extra_parameters: This Linux/Unix-specific directive allows you to send additional email parameters to Sendmail. For instance, you could use this function to override the originating address defined in the mail() function. Typically, this directive is only of concern to system administrators.

Those of you familiar with email configuration are probably wondering how to perform SMTP authentication when connecting to an SMTP server. The unfortunate answer is that you cannot; this eliminates your ability to use most security-conscious mail services in conjunction with PHP's native email transmission capability. All is not lost, however, because later in this tutorial I'll introduce you to PEAR's Mail package that, among other features, offers SMTP authentication.

Sending Email Using the mail() Function

As aforementioned, if you're running PHP on Linux or Unix, or are able to connect to an SMTP server without SMTP authentication, PHP's mail() function offers by far the easiest solution for sending email. Its prototype follows:

boolean mail(string $to, string $subject, string $message
   [, string $addl_headers [, string $addl_params]])

The $to, $subject, and $message parameters are all self-explanatory, and are all required for the mail() function to operate as expected. The $addl_headers parameter is used to define email headers such as From and Cc. Finally, the $addl_params parameter allows you to modify Sendmail's behavior by passing additional configuration parameters to the program at runtime. Typically, you won't need to use $addl_params, although $addl_headers is often used to set commonplace headers. For instance:

<?php
   mail("jason@example.com", "Welcome to the website", 
        "Thank you for joining!",
        "From:jason@example.org\r\nCc:admin@example.org");
?>

Take particular note of the \r\n escape sequence separating each header. Neglecting to include this can result in unexpected behavior or failure to transmit the message.

Sending Email Using the PEAR Mail Package

As you've seen, the mail() function offers a no-nonsense, no-frills means for transmitting email. However, Windows users likely are greatly limited by PHP's native inability to perform SMTP authentication, not to mention reliance on settings defined within php.ini is going to make moving your website from one server to another somewhat of a chore. One convenient solution that solves both of these issues is PEAR's Mail package, which provides a unified programmatic interface for both identifying the transmission backend (and any configuration-related data such as authentication) and sending the message.

To install Mail, execute the following two commands from your terminal:

%>pear install -o Mail
%>pear install -o Net_SMTP

Once installed, you can configure Mail within your script to identify the SMTP server alongside any connection parameters. In the following example, I use Google's Gmail service (which I use to manage email for the domain wjgilmore.com) to transmit a message:

<?php

   // Include the Mail package
   require "Mail.php";

   // Identify the sender, recipient, mail subject, and body
   $sender    = "wj@wjgilmore.com";
   $recipient = "jason@example.com";
   $subject   = "Thank you for your email!";
   $body      = "I'll get back to you as soon as I can!";

   // Identify the mail server, username, password, and port
   $server   = "ssl://smtp.gmail.com";
   $username = "wj@wjgilmore.com";
   $password = "supersecret";
   $port     = "465";

   // Set up the mail headers
   $headers = array(
      "From"    => $sender,
      "To"      => $recipient,
      "Subject" => $subject
   );

   // Configure the mailer mechanism
   $smtp = Mail::factory("smtp",
      array(
        "host"     => $server,
        "username" => $username,
        "password" => $password,
        "auth"     => true,
        "port"     => 465
      )
   );

   // Send the message
   $mail = $smtp->send($recipient, $headers, $body);

   if (PEAR::isError($mail)) {
      echo ($mail->getMessage());
   }

?>

The code found in this example should be fairly straightforward, so I won't elaborate on its contents, although it's worth noting that in this particular case PHP's OpenSSL extension must be enabled, because Gmail requires an SSL connection in addition to SMTP authentication. If your server doesn't require SSL, you should be able to authenticate without necessarily reconfiguring PHP to include this extension.

Sending Email Using the Zend Framework

The first two solutions provided in this tutorial progressively solve various obstacles you'll encounter when sending email through a PHP script. However, many unresolved tasks remain. For instance, how can you send HTML-formatted email? Include attachments? If you're looking for the total package when it comes to sending email, capable of doing everything you could possibly conceive in this regards, look no further than the Zend Framework.

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 concluding section, I'll presume you're familiar with the Zend Framework and therefore focus upon my particular approach to 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 = smtp.gmail.com
email.username   = wj@wjgilmore.com
email.password   = supersecret
email.support    = support@wjgilmore.com

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,
                                   $mailConfigs);
Zend_Mail::setDefaultTransport($tr);

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->setFrom($this->config->email->from_admin);
   $mail->addTo("jason@example.com");
   $mail->setSubject("Your account has been created");

   $email = "Thank you for registering!";

   $mail->setBodyText($email);
   $mail->send();

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

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

$mail->createAttachment("brochure.pdf");

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

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

Where to From Here?

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:

About the Author

Jason Gilmore is founder of a web development and consulting firm based out of Columbus, Ohio. Formerly Apress' open source editor, Jason fostered the development of more than 60 books, along the way helping to transform their open source line into one of the industry's most respected publishing programs. He's the author of several books, including the best-selling Beginning PHP and MySQL: From Novice to Professional (currently in its third edition), Beginning PHP and PostgreSQL: From Novice to Professional, and Beginning PHP and Oracle: From Novice to Professional.

Jason is cofounder of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer's conference, and was a member of the 2008 MySQL Conference speaker selection board. Jason has over 100 articles to his credit within prominent publications such as Developer.com, Linux Magazine, and TechTarget.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date