Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am sending emails successfully using following code. But now I want to attach a text file (example: test.txt) with email. Any Idea?

require_once "Mail.php";

$from = "Usman <[email protected]>";
$to = "Naveed <[email protected]>";
$subject = "subject";
$body = "";

$host = "smtp.gmail.com";
$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 ) );

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

if ( PEAR::isError($mail) ) {
echo( "<p>" . $mail->getMessage() . "</p>" );
} else {
echo( "<p>Message successfully sent!</p>" );
}
like image 635
Naveed Avatar asked Jul 21 '10 13:07

Naveed


People also ask

How email attachment is send with PHP?

The PHP mail() function with some MIME type headers can be used to send email with attachment in PHP. In the following example code, MIME and Content-Type headers are used with mail() function to send email with attachment using PHP. $to – Recipient email address. $from – Sender email address.


2 Answers

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); 
like image 107
Maerlyn Avatar answered Oct 17 '22 10:10

Maerlyn


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.

like image 27
apiri Avatar answered Oct 17 '22 09:10

apiri