I have been trying for some time to make a code in php to send a file from a form.
The form works, it uploads both the information and the file to the server.
I submit the form with AJAX.
Problem:
When I do email tests, I only receive the message… without an attachment, or it doesn’t even reach on the Google email. When I remove the line of code for the attachment, I also receive the message on google mail.
In short, the code works perfectly if I remove the line of code for adding the attachment.
Can someone help me?
I am a beginner in PHP.
require __DIR__ . '/../../vendor/autoload.php';
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
use PHPMailerPHPMailerSMTP;
$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = Config::SMTP_HOST;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = Config::SMTP_PORT;
$mail->Username = Config::SMTP_USERNAME;
$mail->Password = Config::SMTP_PASSWORD;
$mail->addCustomHeader('MIME-Version', '1.0');
$mail->addCustomHeader('Content-type', 'text/html; charset=UTF-8');
$mail->addCustomHeader('Viewport', 'width=device-width, initial-scale=1.0');
$mail->ContentType = 'text/html; charset=UTF-8';
$mail->setFrom($customerEmail, $customerName);
$mail->addAddress($sellerEmail, $sellerName);
$mail->addAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
$mail->IsHTML(true);
$mail->Subject = $subjectForSeller;
$mail->Body = $messageForSeller;
$mail->send();
2
Answers
Remove this lines:
and Check size (less than 25 meg) and mime type of file (not EXE, APK, etc.) and upload it on your host. Then use path of file on the host and a clean name (just number/alphabets with extension) in $mail->addAttachment.
Try the following code, which I verified to be working (sending an E-Mail w/ attachment to my GMail):
While the line
is for debugging purposes only, you should always use is_uploaded_file for verification.
And this is the HTML form I used for testing:
Edit: I’ve tried your code snippet as well and it’s working just fine, so there might me something wrong with your file or file upload. You may want to add the form, the AJAX call and a link to the test file to your question.