Sending Authenticated SMTP Email with attachments using PHP – Pear Mail

We recently had to reconfigure how mail was being sent using PHP and oddly there were many sources out there that just didn’t seem to work. So here’s some sample code we put together that should work if you’re trying to send authenticated SMTP email with an attachment using Pear Mail.

require_once "Mail.php"; // PEAR Mail package
require_once ('Mail/mime.php'); // PEAR Mail_Mime packge

$from = "Your Mom <>";
$to = "Me <>";
$subject = 'Call Me!';

$headers = array ('From' => $from,'To' => $to, 'Subject' => $subject);

// text and html versions of email.
$text = 'Hi son, what are you doing?nnHere's an picture of a cat for you.';
$html = 'Hi son, what are you doing?<br /><br />Here's an picture of a cat for you.';

// attachment
$file = '/catpictures/cat.jpg';
$crlf = "n";

$mime = new Mail_mime($crlf);
$mime->addAttachment($file, 'text/plain');

$body = $mime->get();
$headers = $mime->headers($headers);

$host = "";
$username = "";
$password = "yourpassword";

$smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true,
 'username' => $username,'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
	echo("<p>" . $mail->getMessage() . "</p>");
else {
	echo("<p>Message successfully sent!</p>");