user5876330 user5876330 - 5 months ago 24
PHP Question

Why mail attachment in php send encoded contents instead of PDF file

Hello Recently i working on php mail attachment but i faced a problem when i send my attachment to somebody email it will show like

This is my first mail.Content-Type: application/octet-stream; name="PankajChandwani.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="PankajChandwani.pdf"

JVBERi0xLjQKJaqrrK0KNCAwIG9iago8PAovQ3JlYXRvciAoQXBhY2hlIEZPUCBWZXJzaW9uIDEu
MSkKL1Byb2R1Y2VyIChBcGFjaGUgRk9QIFZlcnNpb24gMS4xKQovQ3JlYXRpb25EYXRlIChEOjIw
MTYwNjIzMDY0OTM3WikKPj4KZW5kb2JqCjUgMCBvYmoKPDwKICAvTiAzCiAgL0xlbmd0aCAxMSAw
IFIKICAvRmlsdGVyIC9GbGF0ZURlY29kZQo+PgpzdHJlYW0KeJydlndYU+cex99zTvZgJCFsCHuG
pUAAkRGmgAzZohCSAAESICQM90BUsKKoyFIEKYpYsFqG1IkoDori3g1SBJRarOLC0USep/X29t7b
2+8f53ye3/v7vef9jfd5DgCkgEyuMBdWAUAokogj/L0ZsXHxDOwAgAEeYIA9ABxubrZXWFgwkCvQ
l83IlTuBf9GrmwBSvK8xFXuB/0+q3GyxBAAoTM6zePxcrpyL5JyZL8lW2CflTEvOUDCMUrBYfkA5
ayg4dYatP/vMsKeCeUIRT86Rcs7mCXkK7pXzhjwpX86IIpfiPAE/X87X5WycKRUK5PxGESvkc+Q5


encoded contents this is my mail attachment code in php

$path = get_home_path();
$filename='Pankaj.pdf';
$file = $path.'wp-admin'.'/'.$filename;
//print_r($file);
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$to = $_REQUEST['email'];
$subject = 'Test email';
$message = "Hello World!\n\nThis is my first mail.";
$message .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$message .= $content."\r\n\r\n";
$headers = "From: ankits8@gmail.com\r\nReply-To: ankits8@gmail.com";
$mail_sent = @mail( $to, $subject, $message, $headers );
echo $mail_sent ? "Mail sent" : "Mail failed"; die;


i can not estimate where i wrong please find out error and help thanks.

Answer

To use PHPMailer:

Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer Extract the archive and copy the script's folder to a convenient place in your project. Include the main script file -- require_once('path/to/file/class.phpmailer.php'); Now, sending emails with attachments goes from being insanely difficult to incredibly easy:

$email = new PHPMailer();
$email->From      = 'you@example.com';
$email->FromName  = 'Your Name';
$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();

It's just that one line $email->AddAttachment(); -- you couldn't ask for any easier.

If you do it with PHP's mail() function, you'll be writing stacks of code, and you'll probably have lots of really difficult to find bugs.