1

I'm using PHPMailer on a simple contact form, and to submit that form I'm using jQuery AJAX. The contact form works as expected along with AJAX, and now that everything is working I'm tackling this issue.

File attachments aren't included in the email sent by PHPMailer when submitting the form via AJAX.

How can I also send attachments when submitting the form with jQuery AJAX?

  • PHPMailer has nothing to do with Ajax. You're simply handling the uploads wrong. Base your code on the multiple file upload example provided with PHPMailer. – Synchro May 07 '16 at 06:27
  • You might find PHP is changing the form-4-file to form_4_file. This might be useful http://stackoverflow.com/questions/1436166/php-replace-dashes-in-object-variables-with-underscores – Steve May 07 '16 at 06:29
  • What does this mean? I can't name my input fields with '-'? Is this why my attachments aren't sent? –  May 07 '16 at 06:32
  • It may be the filenames that are causing the problem. If you have tested that the `if( isset($_FILES['form-4-file']) && $_FILES['form-4-file']['error'] == UPLOAD_ERR_OK )` does work - by echoing "it works" for example, then try echoing the file names. http://stackoverflow.com/questions/11764156/send-file-attachment-from-form-using-phpmailer-and-php might also help. – Steve May 07 '16 at 06:36
  • The files are received when I disable AJAX. The PHP part of the attachment is working, It's when the form is submitted with AJAX that the attachments don't work. I don't receive the echo when form is submitted with ajax –  May 07 '16 at 06:42
  • Solve one problem at a time - upload your files, then mail them. If you try to do both at once and it doesn't work, you don't know where the problem is. It sounds like you need to log precisely what is turning up in your ajax submission. – Synchro May 08 '16 at 16:29

1 Answers1

1

You need to set headers of mail. Some of header examples are below:-

$header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
Atul Rai
  • 242
  • 2
  • 10