send attachment from form with phpmailer not working

余生颓废 提交于 2019-12-02 04:22:31

问题


After searching stackoverflow i didnt get any answer to my problem. The problems is that i have a form with upload button so when the user submits a file that will be emailed to me immediately. I use phpmailer but i only get message instead of message + attachment. Any idea where the problem is?

PS im open to simpler ways to do this. Thank you.

here is the PHPcode

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\-]+\.)*+[a-z]{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']);
   }
}
?>

here is the form 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 -->

Things to notice: the php file is called through 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;
  });

回答1:


Solve one problem at a time: fix your upload first, then worry about emailing it. You need to call move_uploaded_file for safety, check that it's all OK, and then try to send it. There is an example provided with PHPMailer that does exactly what you need.



来源:https://stackoverflow.com/questions/28233901/send-attachment-from-form-with-phpmailer-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!