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 ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.