После поиска stackoverflow я не получил никакого ответа на мою проблему. Проблемы в том, что у меня есть форма с кнопкой загрузки, поэтому, когда пользователь отправляет файл, который будет немедленно отправлен мне по электронной почте. Я использую phpmailer, но я получаю сообщение вместо сообщения + вложения. Любая идея, где проблема?
PS im для более простых способов сделать это. Спасибо.
вот код PHP
if($_POST) { $name = trim(stripslashes($_POST['uploadName'])); $email = trim(stripslashes($_POST['uploadEmail'])); $subject = trim(stripslashes($_POST['uploadSubject1'])); $contact_address = trim(stripslashes($_POST['uploadAddress'])); $contact_tk = trim(stripslashes($_POST['uploadTk'])); $contact_poli = trim(stripslashes($_POST['uploadCity'])); $contact_region = trim(stripslashes($_POST['uploadRegion'])); $tmp_name = $_FILES['fileToUpload']['tmp_name']; $type = $_FILES['fileToUpload']['type']; $file_name = $_FILES['fileToUpload']['name']; $size = $_FILES['fileToUpload']['size']; // Check Name if (strlen($name) < 2) { $error['name'] = "add name"; } // Check Email if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[az]{2}/is', $email)) { $error['email'] = "enter mail"; } // Check address if (strlen($contact_address)< 5) { $error['message'] = "address please"; } // Check ΤΚ if (strlen($contact_tk)!=5) { $error['message1'] = "enter PO"; } // Check city if (strlen($contact_poli)=='') { $error['message2'] = "city?"; } // Check region if (strlen($contact_region) < 4) { $error['message3'] = "your region"; } // Subject if ($subject == '') { $subject = "uploaded file"; } /* Start of headers */ // Set From: header // Set Message $message = "from " . $name . "<br />"; $message .= "to " . $email . "<br />"; $message .= "address " . $contact_address . "<br />"; $message .= "PO " . $contact_tk . "<br />"; $message .= "City". $contact_poli . "<br />"; $message .= "region". $contact_region . "<br />"; /////////////////////////////////////////////////CHANGES FROM NOW ON///////////////////////////////// if (array_key_exists('fileToUpload', $_FILES)) { // First handle the upload // Don't trust provided filename - same goes for MIME types // See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['fileToUpload']['name'])); if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) { // Upload handled successfully // Now create a message // This should be somewhere in your include_path require 'PHPMailerAutoload.php'; $mail = new PHPMailer; $mail->setFrom($siteOwnersEmail, 'First Last'); $mail->addAddress('some1@some.com', 'John Doe'); $mail->Subject = 'PHPMailer file sender'; $mail->msgHTML("My message body"); // Attach the uploaded file $mail->addAttachment($uploadfile, 'My uploaded file'); if (!$mail->send()) { echo 'Message was not sent.'; echo 'Mailer error: ' . $mail->ErrorInfo; $response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null; $response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null; $response .= (isset($error['message'])) ? $error['message'] . "<br />\n" : null; $response .= (isset($error['message1'])) ? $error['message1'] . "<br />\n" : null; $response .= (isset($error['message2'])) ? $error['message2'] . "<br />\n" : null; $response .= (isset($error['message3'])) ? $error['message3'] . "<br />\n" : null; $response .= (isset($error['message4'])) ? $error['message4'] . "<br />\n" : null; echo $response; } else { echo '<i class="fa fa-check"></i>your message was sent!<br> <script>document.getElementById("uploadForm").reset();</script>'; $_POST = array(); } } else { $msg = 'Failed to move file to ' . $uploadfile; } //require 'class.phpmailer.php'; //$mail = new PHPMailer(); //$mail->AddAddress($siteOwnersEmail, "website"); //$mail->Subject = "uploaded file test"; //$mail->Body = $message; //$mail->AddAttachment($_FILES['fileToUpload']['tmp_name'], $_FILES['fileToUpload']['name']); } } ?>
вот форма HTML:
<form action="" method="post" id="uploadForm" name="uploadForm" enctype="multipart/form-data"> <fieldset> <div> <label for="uploadName">name<span class="required">*</span></label> <input type="text" value="" size="35" id="uploadName" name="uploadName"> </div> <div> <label for="uploadEmail">Email<span class="required">*</span></label> <input type="text" value="" size="35" id="uploadEmail" name="uploadEmail"> </div> <div> <label for="uploadSubject">address<span class="required">*</span></label> <input type="text" value="" size="35" id="uploadAddress" name="uploadAddress"> </div> <div> <label for="uploadMessage">po<span class="required">*</span></label> <input type="text" value="" size="35" id="uploadTk" name="uploadTk"> </div> <div> <label for="uploadMessage">city<span class="required">*</span></label> <input type="text" value="" size="35" id="uploadCity" name="uploadCity"> </div> <div> <label for="uploadMessage">region<span class="required">*</span></label> <input type="text" value="" size="35" id="uploadRegion" name="uploadRegion"> </div> <div> <label id="fileToUpload" for="uploadMessage2">send file<span class="required">*</span></label> <input type="file" name="fileToUpload" id="fileToUpload"> <button class="submit1" name="submit1">UPLOAD</button> <!--<input type="submit" value="Upload File" name="submit1">--> <span id="image-loader1"> <img alt="" src="images/loader.gif"> </span> </div> </fieldset> </form> <!-- Form End -->
Что следует заметить: php-файл вызывается через ajax
$('form#uploadForm button.submit1').click(function() { $('#image-loader1').fadeIn(); var uploadName = $('#uploadForm #uploadName').val(); var uploadEmail = $('#uploadForm #uploadEmail').val(); var uploadAddress= $('#uploadForm #uploadAddress').val(); var uploadTk= $('#uploadForm #uploadTk').val(); var uploadCity= $('#uploadForm #uploadCity').val(); var uploadRegion= $('#uploadForm #uploadRegion').val(); var fileToUpload= $('#uploadForm #fileToUpload').val(); var data = 'uploadName=' + uploadName+ '&uploadEmail=' + uploadEmail + '&uploadAddress=' + uploadAddress + '&uploadTk=' + uploadTk + '&uploadCity=' + uploadCity + '&uploadRegion=' + uploadRegion + '&fileToUpload=' + fileToUpload; $.ajax({ type: "POST", url: "inc/sendFile-.php", data: data, success: function(msg) { // Message was sent if (msg == 'OK') { $('#image-loader1').fadeOut(); $('#message-warning1').hide(); $('#uploadForm').fadeOut(); $('#message-success1').fadeIn(); } // There was an error else { $('#image-loader1').fadeOut(); $('#message-warning1').html(msg); $('#message-warning1').fadeIn(); } } }); return false; });
Решите одну проблему за один раз: сначала исправьте свою загрузку, а затем подумайте о ее отправке по электронной почте. Вам нужно вызвать move_uploaded_file
для обеспечения безопасности, убедитесь, что все в порядке, а затем попробуйте отправить его. Существует пример, предоставляемый PHPMailer, который делает именно то, что вам нужно.