O'Reilly logo

PHP Cookbook by Adam Trachtenberg, David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

17.1. Sending Mail

Problem

You want to send an email message. This can be in direct response to a user’s action, such as signing up for your site, or a recurring event at a set time, such as a weekly newsletter.

Solution

Use PEAR’s Mail class:

require 'Mail.php';

$to = 'adam@example.com';

$headers['From'] = 'webmaster@example.com';
$headers['Subject'] = 'New Version of PHP Released!';

$body = 'Go to http://www.php.net and download it today!';

$message =& Mail::factory('mail');
$message->send($to, $headers, $body);

If you can’t use PEAR’s Mail class, use PHP’s built-in mail( ) function:

$to = 'adam@example.com';
$subject = 'New Version of PHP Released!';
$body = 'Go to http://www.php.net and download it today!';
  
mail($to, $subject, $body);

Discussion

PEAR’s Mail class allows you to send mail three ways. You indicate the method to use when instantiating a mail object with Mail::factory( ).

  • To send mail using an external program such as sendmail or qmail, pass sendmail.

  • To use an SMTP server, pass smtp.

  • To use the built-in mail( ) function, pass mail. This tells Mail to apply the settings from your php.ini .

To use sendmail or smtp, you have to pass a second parameter indicating your settings. To use sendmail, specify a sendmail_path and sendmail_args:

$params['sendmail_path'] = '/usr/sbin/sendmail';
$params['sendmail_args'] = '-oi -t';

$message =& Mail::factory('sendmail', $params);

One good value for sendmail_path is /usr/lib/sendmail. Unfortunately, sendmail tends to jump around ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required