doubu4406 2016-05-25 05:23
浏览 34
已采纳

PHPMailer - 代码似乎什么都不做

I need help, I am getting an undefined error and it is definitely being caused by my code that deals with attachments which is at the top of the PHP file. I know this because if I comment it out I don't get that error.

The next thing is I am using XAMPP and I followed a couple tutorials to get sendmail in the php.ini file and C://xampp/sendmail/senmail.ini setup so I was hoping that it would actually send an email via gmail when I tested the form but I haven't gotten any through yet.

I don't know where to begin, I've used two tutorials to make my php code, please take a look.

<?php
header('Content-type: application/json');
$status = array(
    'type'=>'success',
    'message'=>'Thank you for contact us. As early as possible  we will contact you '
);

//Added to deal with Files
require_once('../PHPMailer/class.phpmailer.php')
    //Get the uploaded file information
    $name_of_uploaded_file =
        basename($_FILES['uploaded_file']['name']);

    //get the file extension of the file
    $type_of_uploaded_file =
        substr($name_of_uploaded_file,
        strrpos($name_of_uploaded_file, '.') + 1);

    $size_of_uploaded_file =
        $_FILES["uploaded_file"]["size"]/1024;//size in KBs

    //Settings
    $max_allowed_file_size = 10240; // size in KB
    $allowed_extensions = array("jpg", "jpeg", "gif", "bmp","png");

    //Validations
    if($size_of_uploaded_file > $max_allowed_file_size )
    {
      $errors .= "
 Size of file should be less than $max_allowed_file_size (~10MB). The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.";
    }

    //------ Validate the file extension -----
    $allowed_ext = false;
    for($i=0; $i<sizeof($allowed_extensions); $i++)
    {
      if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
      {
        $allowed_ext = true;
      }
    }

    if(!$allowed_ext)
    {
      $errors .= "
 The uploaded file is not supported file type. ".
      " Only the following file types are supported: ".implode(',',$allowed_extensions);
    }

    //copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission
    $path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
    $tmp_path = $_FILES["uploaded_file"]["tmp_name"];

    if(is_uploaded_file($tmp_path))
    {
      if(!copy($tmp_path,$path_of_uploaded_file))
      {
        $errors .= '
 error while copying the uploaded file';
      }
    }
//--end


$name = @trim(stripslashes($_POST['name'])); 
$clientemail = @trim(stripslashes($_POST['email'])); 
$subject = @trim(stripslashes($_POST['subject'])); 
$message = @trim(stripslashes($_POST['message']));

$body = 'Name: ' . $name . "

" . 'Email: ' . $clientemail . "

" . 'Subject: ' . $subject . "

" . 'Message: ' . $message;

//$success = @mail($email_to, $subject, $body, 'From: <'.$email_from.'>'); //This is the old PHP (no file attachment allowed)

$email = new PHPMailer();
$email->From      = $clientemail;
$email->FromName  = $name;
$email->Subject   = $subject;
$email->Body      = $body;  
$email->AddAddress( 'badrush14@hotmail.com' ); //Send to this email

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$success = $email->AddAttachment( $path_of_uploaded_file , $name_of_uploaded_file );

return $email->Send();

echo json_encode($status);
die;
  • 写回答

1条回答 默认 最新

  • dongshi3605 2016-05-25 06:05
    关注

    First; You are returning a Boolean Flag before sending back the JSON Response. Once you return a value, any statement below the return Keyword is ignored. Thus, you might not be getting the result you want. Second; You might need to explicitly tell PHPMailer how to send the Email. Third, You forgot the closing Semi-Colon ( ; ) on the require_once line. The code below has comments to indicate what you may have missed:

        <?php
            header('Content-type: application/json');
    
            // WE SHOULD ASSUME THAT THE EMAIL WAS NOT SENT AT FIRST UNTIL WE KNOW MORE.
            // WE ALSO ADD AN ATTACHMENT KEY TO OUR STATUS ARRAY TO INDICATE THE STATUS OF OUR ATTACHMENT:  
            $status = array(
                'type'          =>'Error',
                'message'       =>'Couldn\'t send the Email at this Time. Something went wrong',
                'attachement'   =>'Couldn\'t attach the uploaded File to the Email.'
            );
    
            //Added to deal with Files
            // YOU MISSED A CLOSING SEMI-COLON HERE... ;-)
            require_once('/PHPMailer/class.phpmailer.php');  //Double check this path
            //Get the uploaded file information
            $name_of_uploaded_file =
                basename($_FILES['uploaded_file']['name']);
    
            //get the file extension of the file
            $type_of_uploaded_file =
                substr($name_of_uploaded_file,
                    strrpos($name_of_uploaded_file, '.') + 1);
    
            $size_of_uploaded_file =
                $_FILES["uploaded_file"]["size"]/1024;//size in KBs
    
            //Settings
            $max_allowed_file_size = 10240; // size in KB
            $allowed_extensions = array("jpg", "jpeg", "gif", "bmp","png");
    
            //Validations
            if($size_of_uploaded_file > $max_allowed_file_size )
            {
                $errors .= "
     Size of file should be less than $max_allowed_file_size (~10MB). The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.";
            }
    
            //------ Validate the file extension -----
            $allowed_ext = false;
            for($i=0; $i<sizeof($allowed_extensions); $i++)
            {
                if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
                {
                    $allowed_ext = true;
                }
            }
    
            if(!$allowed_ext)
            {
                $errors .= "
     The uploaded file is not supported file type. ".
                    " Only the following file types are supported: ".implode(',',$allowed_extensions);
            }
    
            //copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission
            $path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
            $tmp_path = $_FILES["uploaded_file"]["tmp_name"];
    
            if(is_uploaded_file($tmp_path))
            {
                if(!copy($tmp_path,$path_of_uploaded_file))
                {
                    $errors .= '
     error while copying the uploaded file';
                }
            }
        //--end
    
    
            $name = @trim(stripslashes($_POST['name']));
            $clientemail = @trim(stripslashes($_POST['email']));
            $subject = @trim(stripslashes($_POST['subject']));
            $message = @trim(stripslashes($_POST['message']));
    
            $body = 'Name: ' . $name . "
    
    " . 'Email: ' . $clientemail . "
    
    " . 'Subject: ' . $subject . "
    
    " . 'Message: ' . $message;
    
            //$success = @mail($email_to, $subject, $body, 'From: <'.$email_from.'>'); //This is the old PHP (no file attachment allowed)
    
            $email              = new PHPMailer();
            $email->From        = $clientemail;
            $email->FromName    = $name;
            $email->Subject     = $subject;
            $email->Body        = $body;
            $email->AddAddress( 'badrush14@hotmail.com' ); //Send to this email
    
            // EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP BUILT IT MAIL FUNCTION    
            $email->isMail();
    
    
            // THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE:
            // KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT 
            // WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY...   
            if($email->AddAttachment( $path_of_uploaded_file , $name_of_uploaded_file )){
                $status['attachment']   = 'Uploaded File was successfully attached to the Email.';  
            }
    
            // NOW, TRY TO SEND THE EMAIL ANYWAY:
            try{
                $emailStatus    = $email->send();
                $status['type']     = 'success';
                $status['message']  = 'Thank you for contact us. As early as possible  we will contact you.';   
            }catch(Exception $e){
                $status['type']     ='Error';
                $status['message']  ='Couldn\'t send the Email at this Time. Something went wrong';     
            }   
    
            // WHEN YOU RETURN THE BOOLEAN FLAG OF THE RESULT OF SENDING AND EMAIL; THE PROGRAM ENDS IMMEDIATELY
            //AND THUS YOU CANNOT RESPOND WITH JSON... THUS, THIS LINE IS NOT HELPFUL TO YOU...
            //return $email->Send();
    
            // SIMPLY, RETURN THE JSON DATA...
            die (json_encode($status));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fx2n系列plc的自控成型机模拟
  • ¥15 时间序列LSTM模型归回预测代码问题
  • ¥50 使用CUDA如何高效的做并行化处理,是否可以多个分段同时进行匹配计算处理?目前数据传输速度有些慢,如何提高速度,使用gdrcopy是否可行?请给出具体意见。
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),如何通过环岛的原理及完整代码
  • ¥20 机器学习或深度学习问题?困扰了我一个世纪,晚来天欲雪,能饮一杯无?
  • ¥15 c语言数据结构高铁订票系统
  • ¥15 关于wkernell.PDB加载的问题,如何解决?(语言-c#|开发工具-vscode)
  • ¥100 某宝多次访问被拒绝,求解
  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!