Search code examples
phpemailpearmime

MIME file attachment is not opening


My code is

<?php

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

 $from = "<[email protected]>";
 $to = "<[email protected]>";
 $subject = "Hi!";


$host = "ssl://smtp.googlemail.com";
$port = "465";
$username = "[email protected]";
$password = "example";

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


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


 // attachment
 $file = '/var/www/html/formsubmit/TodoList/upload/abc.pdf';
 $crlf = "n";
 $text="Helllooooo";
 $html = "<html> <head> <title>Mail test</title> </head>  <body>something</body></html>";

$mime = new Mail_mime($crlf);
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
if($mime->addAttachment($file))
{
   echo "Success";
}
else 

{
    echo "Failed";
}


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


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


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

The attachment is unable to open even after downloading it.

Mail is coming in inbox and attachment is also there.But the attachment seems like txt file.but I am actually attaching a pdf file. I used SMTP mail and MIME mail functions.

Pls help me.


Solution

  • The relevant code in the mail is:

    Content-Transfer-Encoding: base64
    Content-Type: application/octet-stream;
     name=abc.pdf
    Content-Disposition: attachment;
     filename=abc.pdf;
     size=4997278
    

    The content type is a generic one; try to use application/pdf as second parameter to addAttachment().


    Also, NEVER post your real mail address and password anywhere.