Badrush
Badrush

Reputation: 1287

PHPMailer - Code seems to do nothing

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 .= "\n 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 .= "\n 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 .= '\n 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 . "\n\n" . 'Email: ' . $clientemail . "\n\n" . 'Subject: ' . $subject . "\n\n" . '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( '[email protected]' ); //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;

Upvotes: 0

Views: 133

Answers (1)

Poiz
Poiz

Reputation: 7617

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 .= "\n 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 .= "\n 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 .= '\n 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 . "\n\n" . 'Email: ' . $clientemail . "\n\n" . 'Subject: ' . $subject . "\n\n" . '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( '[email protected]' ); //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));

Upvotes: 1

Related Questions