Search code examples
emailphpmailerattachment

PHPMailer attachment is not receiving


I have written code for sending mail with pdf file as attachment , mail sending is working. I used class.phpmailer.php. Below is my code.

$mpdf=new mPDF();   
$mpdf->ignore_invalid_utf8 = true;
$stylesheet = file_get_contents('appstyle_pdf.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($output);
$comname = preg_replace("/[^A-Za-z0-9]/","",$_POST['company']);
$name = $dirname.str_replace(" ","-",$comname)."_".$time_stamp.".pdf";        
$mpdf->Output($name,"F");       
$filename = basename($name);        
$file_size = filesize($name);       
$content = chunk_split(base64_encode(file_get_contents($name)));
$mail = new PHPMailer;
$msg = 'Message';
$body = '<html><body><p>' . $msg . '</p></body></html>'; //msg contents
$body = preg_replace("[\\\]", '', $body);
$mail->AddReplyTo('[email protected]', "ACIC");
$mail->SetFrom('[email protected]', "ACIC Order");
$address = '[email protected]'; //email recipient
$mail->AddAddress($address, "NAME");
$mail->Subject = 'SUBJECT of ACIC order form';
$mail->MsgHTML($body);
$mail->AddStringAttachment($content , $filename); 
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent Successfully please check attachement!";
}   

When I use the above code attachment is coming to mail but file is corrupting. The error message is like "Adobe reader could not open abc.pdf because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)."


Solution

  • Why are you doing this?

    $content = chunk_split(base64_encode(file_get_contents($name)));
    ...
    $mail->AddStringAttachment($content , $filename); 
    

    That's completely unnecessary. Just do this:

    $mail->addAttachment($name);
    

    Also I suspect you are using an old version of PHPMailer; get the latest from github.