Using PEAR to send Email via SMTP
The php mail() function is great. Super easy to use and no setup required. But it would seem some spam filters are often suspicious of email sent this way and rightly or wrongly I just don’t feel it is reliable enough.
I’m currently redesigning the Goonanism home page – it’s starting to look a bit stale (launch TBA) and I thought it was important that the contact page on the new site was as reliable as possible.
Knowing that my web hosts supported PEAR I decided to use PEAR’s Mail function instead. So I wrote the following script:
< ?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
require_once("Mail.php");
$from = 'Website Enquiry
$to = "Hammy Goonan
$subject = "Website enquiry";
$body = $message;
$host = "hostdetails";
$username = "username";
$password = "password";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject
);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password,
'port' => '25'
)
);
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo($mail->getMessage());
}
else {
echo("Message successfully sent!");
}
?>
This gave me an error saying:
Class 'Net_SMTP' not found in /usr/local/php52/pear/Mail/smtp.php on line 210
So, using siteground as my host, I followed this tutorial.
Having uploaded the Net_STMP files and setting up my php.ini files I then got this error:
Fatal error: require_once() [function.require]: Failed opening required 'PEAR.php' (include_path='.:/usr/lib/php:/usr/local/lib/php:/home/goonanis/pear') in /home/goonanis/pear/Net_SMTP/SMTP.php
So it was clear to me that because of the new php.ini file, I would have to upload all the dependant packages to get this working.
Having uploaded various packages I was still getting an error saying:
Call to undefined method PEAR_Error::send()
Reading through various forums I realised that Mail::factory() will return a PEAR_Error object upon failure. So $smtp became a PEAR_Error so when I tried to call PEAR_Error::send() it wasn’t there, hence the error.
When I print_r() $smtp the PEAR_Error Object was actually throwing an error saying:
Unable to find class for driver smtp
A much more useful error message.
I only mention all of this because I had a lot of trouble sorting through forums to find this information out.
Anyway, the long and the short of it was that I needed to have the following packages and file structure for the PEAR Mail function to work:
pear
/Mail
/RFC822.php
/mail.php
/mock.php
/null.php
/sendmail.php
/smtp.php
/smtpmx.php
/Net
/SMTP.php
/Socket.php
/Mail.php
/PEAR.php
/PEAR5.php
Which you can find in the following PEAR packages:
- Pear
- Net_Socket
- Net_STMP
I hope that helps!