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 <mom@mom.com>";
$to = "Me <me@me.com>";
$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->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'text/plain');

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

$host = "smtp.yourserver.com";
$username = "me@me.com";
$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>");
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>