PHP: How to send email with attachment using smtp settings?

Found this code as one of the first hits of the google://pear mail attachment search.

include('Mail.php');
include('Mail/mime.php');

$text = 'Text version of email';
$html = '<html><body>HTML version of email</body></html>';
$file = './files/example.zip';
$hdrs = array(
              'From'    => '[email protected]',
              'To'      => '[email protected]',
              'Subject' => 'Test mime message'
              );

$mime = new Mail_mime();

$mime->setTXTBody($text);
$mime->setHTMLBody($html);

$mime->addAttachment($file,'application/octet-stream');

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

$mail =& Mail::factory('mail', $params);
$mail->send('[email protected]', $hdrs, $body); 

If you additionally make use of the PHP PEAR Mail_Mime module it provides the appropriate handling and encoding to incorporate attachments as part of your email.


here is the code you're looking for:

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

$from = "Robert Davis <[email protected]>";
$to = "Sam Hill <[email protected]>";
$subject = 'Test mime message with an attachment';

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

$text = 'Text version of email';// text and html versions of email.
$html = '<html><body>HTML version of email. <strong>This should be bold</strong></body>        </html>';

$file = './sample.txt'; // attachment
$crlf = "\n";

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

//do not ever try to call these lines in reverse order
$body = $mime->get();
$headers = $mime->headers($headers);

$host = "sasl.smtp.pobox.com";
$username = "[email protected]";
$password = "Kdu48Adi3";

$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>");
}
?>