user5876330 user5876330 - 1 year ago 63
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"


encoded contents this is my mail attachment code in php

$path = get_home_path();
$file = $path.'wp-admin'.'/'.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
$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:\r\nReply-To:";
$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 Source

To use PHPMailer:

Download the PHPMailer script from here: 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      = '';
$email->FromName  = 'Your Name';
$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$email->AddAddress( '' );

$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.