The PHP builtin function, mail() can be used to send email using either SMPT or using the operating system’s sendmail program. These features can be configured in the php.ini file, but I found I was having problems authenticating to my smtp relay server, and I wanted to minimize the number of SpamAssassin test failures so my messages would go to the recipients’ inboxes instead of their spam folders.
This post is about the gotchas I dealt with, not a tutorial on sending email in general.
First of all, the PHP mail() function does not let you set up authentication with an smtp relay so far as I can tell, so that’s out. And I have nothing to contribute to using sendmail.
The PEAR repository has two packages that can be used: Mail.php lets you pick among mail(), sendmail, and smtp for sending message; Mail/mime.php lets you set up MIME messages. It seems that Mail/mail.php is another “good” package to use because it provides a mail() function to use for actually sending the email that is better than PHP's builtin mail() function. I can’t say anything about that because I simply used it without testing the option of using the builtin mail().
Here is an outline of the code I ended up with, followed by some notes:
$hdrs = array(
'From' => "$sender_name <$sender_email>",
'To' => "$recipient_name <$recipient_email>",
'Reply-to' => "$reply_name <$reply_email>",
'Cc' => "$copy1_name <$copy1_email>, $copy2_name <$copy2_email>",
'Bcc' => "$bcc_name <$bcc_email>",
'Date' => date('r'),
'Subject' => "The subject of this message",
'Message-ID' => '<' . uniqid() . '@example>'
$recipents = "$sender_email, $recipient_email, $reply_email, $copy1_email, $copy2_email, $bcc_email";
$crlf = "\n";
$mime = new Mail_mime(array('eol' => $crlf, 'text_charset' => 'utf-8', 'html_charset' => 'utf-8'));
$body = $mime->get();
$hdrs = $mime->headers($hdrs);
$smtpinfo["host"] = "smtp.example.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = $smtp_user;
$smtpinfo["password"] = $smtp_pass;
$smtpinfo["localhost"] = 'example.com';
$smtpinfo["persist"] = false;
$mail =& Mail::factory('smtp', $smtpinfo);
$mime_status = $mail->send($recipient_list, $hdrs, $body);
if ( PEAR::isError($mime_status) )
error_exit('Unable to send email: '. $mime_status->getMessage());
$smtpinfo['debug'] = true;