Search code examples
phpemailsendmailpear

Pear Mail sends email without attachment


I am trying to send mail using PHP PEAR Mail with some attached files. I am reading a text file to get the filenames and then using this to create a filePath from which I can attach the file as per the PEAR addAttachment() syntax. But when I receive the mail it has no attachments.

My code

function sendMail() {
    $pdf_filename = file_get_contents("/tmp/uploads/filelog/pdfFiles.txt");
    $csv_filename = file_get_contents("/tmp/uploads/filelog/csvFiles.txt");

    $text = 'Text version of email';
    $html = '<html><body>HTML version of email</body></html>';
    $csv_file = '/tmp/uploads/csv/' . $csv_filename;
    $pdf_file = '/tmp/uploads/pdf/' . $pdf_filename;
    $crlf = "\n";
    $hdrs = array (
            'From' => '[email protected]',
            'Subject' => 'Test mime message' 
    );

    $mime = new Mail_mime ( array (
            'eol' => $crlf 
    ) );
    $mime->setTXTBody ( $text );
    $mime->setHTMLBody ( $html );
    $mime->addAttachment ( $csv_file, 'text/csv' );
    $mime->addAttachment ( $pdf_file, 'application/pdf' );
    $body = $mime->get ();
    $hdrs = $mime->headers ( $hdrs );
    $mail = & Mail::factory ( 'mail' );
    $mail->send ( '[email protected]', $hdrs, $body );
    if (PEAR::isError ( $mail )) {
        echo ("<p>" . $mail->getMessage () . "</p>");
    } else {
         echo ("<p>Message successfully sent!</p>");
    }
}
sendMail();

Why is this not working? Even though I have confirmed that both files exist on the server.


Solution

  • There were some whitespaces being generated, a simple trim() fixed my problem.

    $csv_trimed = trim($csv_file);
    $pdf_trimed = trim($pdf_file);
    .
    .
    .
    .
    .
    
    $mime->addAttachment ( $csv_trimed, 'text/csv' );
    $mime->addAttachment ( $pdf_trimed, 'application/pdf' );