Janice Zhong
Janice Zhong

Reputation: 878

PHPmailer - Add pdf file as attachment doesn't work

My Goal:

Use AddStringAttachment() to send a auto-generated base64 string as a .pdf file to another email address.

Coding Environment:

I'm working on WordPress with a ajax call passing a base64 string to the server. The size of the string is usually around 30kbs, it can be guaranteed not exceeding over 50kbs. I have MAX_EXECUTION_TIME 120s.

What I've Been Working Through:

I succeeded:

I failed:

My Code:

function sendPdf() {

    $mail = new PHPMailer(true);

    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.hostinger.com';                   // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = '[email protected]';                 // SMTP username
    $mail->Password = 'secret';                         // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipient
    $mail->SetFrom('[email protected]');
    $mail->AddAddress( '[email protected]' );

    $pdf_base64 = $_POST[pdfString];

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject= ' New Application Form ';
    $mail->Body= ' New Application Form From WordPress site ';

    //Attachment
    //$mail->AddStringAttachment($pdf_base64, $_POST[clientName].'_Application.pdf', 'base64', 'application/pdf');
    //$mail->AddAttachment(dirname(__FILE__)."/Qian_Zhong_Application.pdf", 'Qian_Zhong_Application.pdf');

    $error = '';

    if(!$mail->send()){
       $error = 'Mail error: '.$mail->ErrorInfo; 
       echo $error;     
    }else{
        echo 'Message has been sent.';
    }

    exit; // This is required to end AJAX requests properly.

}

Upvotes: 0

Views: 1591

Answers (1)

Synchro
Synchro

Reputation: 37810

The data you pass in to addStringAttachment should be raw binary, not encoded in any way, as PHPMailer will take care of that for you. It will also set the encoding and MIME type from the filename you provide, so you do not need to set them manually.

Using a debugger would allow you to watch the script as it runs so you would be able to see exactly what it’s having trouble with. Any error 500s will cause errors to be logged in your web server logs and will usually provide more info.

I would also recommend against using $_POST[clientName] like that without any filtering or validation - you should never trust user input like that.

Upvotes: 1

Related Questions