November 25, 2014
Hot Topics:

Sending Email with PHP

  • November 5, 2008
  • By W. Jason Gilmore
  • Send Email »
  • More Articles »

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.





Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel