Skip to content
Advertisement

Problem with PHPMailer attaching file (only attaches after page refresh)

I have a script that generates a Certificate upon form submit, as well as sends the generated certificate to the recipients email address. When i enter the details into the HTML form, and submit the form, it fails and comes up with an error saying PHPMailer unable to access the file. But when i click on REFRESH on the browser window, it then succeeds and sends the certificate via email..

My PHPMailer code is below:

<?php include 'settings.php'; //include settings

//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;

//Load Composer's autoloader
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';
require 'PHPMailer-master/src/Exception.php';

 if (isset($_POST['generate'])) {
       $name = ucwords($_POST['name']);
        $customerref = ($_POST['customerref']);
        $date = ($_POST['date']);
        $customeremail = ($POST['customeremail']);
       //Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
   
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host       = 'mail.smtp2go.com';                     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = 'refurbsa.com';                     //SMTP username
    $mail->Password   = 'Y2F6ejMxbGFseTUw';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    //Recipients
    $mail->setFrom('info@electronic-cemetery.com', 'Electronic Cemetery');  // this is the sender's Email address
    $mail->addAddress($_POST['customeremail']);     //Add a recipient
    $mail->addReplyTo('info@electronic-cemetery.com', 'Electronic Cemetery');
    
    
    $mail->AddAttachment (dirname(__FILE__)."/CSD-Certificates/saved-certs/destruction-cert($customerref-$date).png");     //Adds an attachment from a path on the filesystem

    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = 'Your E-Waste Disposal Certificate';
    $mail->Body    = "Good day $name,<br><br>
Thank you very much for making use of our services. Your collection has been processed and I have attached your destruction certificate to this email.  
<br><br>
If you were happy with our service then it would be very much appreciated if you would spare a moment to give us your review <a href='https://www.facebook.com/eastcoastewaste/reviews'>HERE</a>
<br><br>
We look forward to assisting you with all your e-Waste needs in the future.
<br><br>
Wishing you a wonderful day further!
<br><br>
The Electronic Cemetery Team";
   
    $mail->send();
   
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
?>

The HTML Form to input the data is below:

 <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
      <div class="form-group col-sm-12">
        <input type="text" name="name" class="form-control" id="name" placeholder="Enter Name Here...">
      </div>
       <div class="form-group col-sm-12">
        <input type="text" name="weight" class="form-control" id="weight" placeholder="Enter Weight Here...">
      </div>
      <div class="form-group col-sm-12">
        <input type="date" name="date" class="form-control" id="date" placeholder="Enter Date Here...">
      </div>
       <div class="form-group col-sm-12">
        <input type="email" name="customeremail" class="form-control" id="customeremail" placeholder="Enter Email Address Here...">
      </div>
       <div class="form-group col-sm-12">
        <input type="text" name="customerref" class="form-control" id="customerref" placeholder="Enter Customer Reference Here...">
      </div>
      <button type="submit" name="generate" class="btn btn-primary">Generate Certificate and Send to Customer</button>
    </form>
   

And finally the script to generate the certificate:

     <?php 
      if (isset($_POST['generate'])) {
        $name = ($_POST['name']);
        $name_len = strlen($_POST['name']);
          $date = ($_POST['date']);
          $customeremail = ($_POST['customeremail']);
           $customerref = ($_POST['customerref']);
        $weight = ucwords($_POST['weight']);
        if ($weight) {
          $font_size_weight = 50;
        }

        if ($name == "" || $weight == "" || $date == "" || $customeremail == "" || $customerref == "") {
          echo 
          "
          <div class='alert alert-danger col-sm-6' role='alert'>
              Not all form fields have been filled in. Pleaes try again.
          </div>
          ";
        }else{
          echo 
          "
          <div class='alert alert-success col-sm-6' role='alert'>
              Congratulations! The certificate for $name has been generated and sent to $customeremail.</b>
          </div>
          ";

          //designed certificate picture
          $image = "CSD-Certificates/certi.png"; 

          $createimage = imagecreatefrompng($image);

          //this is going to be created once the generate button is clicked
          $output = "CSD-Certificates/saved-certs/destruction-cert($customerref-$date).png";

          //then we make use of the imagecolorallocate inbuilt php function which i used to set color to the text we are displaying on the image in RGB format
          $white = imagecolorallocate($createimage, 254, 254, 254);
          $black = imagecolorallocate($createimage, 0, 0, 0);

          //Then we make use of the angle since we will also make use of it when calling the imagettftext function below
          $rotation = 0;

          //we then set the x and y axis to fix the position of our text name
          $origin_x = 1600;
          $origin_y=700;

          //we then set the x and y axis to fix the position of our text weight
          $origin1_x = 2300;
          $origin1_y=900;
          
           //we then set the x and y axis to fix the position of our text date 1
          $origin2_x = 1850;
          $origin2_y=900;
          
            //we then set the x and y axis to fix the position of our text date at the bottom
          $origin3_x = 2200;
          $origin3_y=1980;
          
           //we then set the x and y axis to fix the position of our text date at the bottom
          $origin4_x = 2200;
          $origin4_y=2180;

          //we then set the differnet size range based on the lenght of the text which we have declared when we called values from the form
          if($name_len<=7){
            $font_size = 50;
            $origin_x = 1600;
          }
          elseif($name_len<=12){
            $font_size = 40;
          }
          elseif($name_len<=15){
            $font_size = 40;
          }
          elseif($name_len<=20){
             $font_size = 40;
          }
          elseif($name_len<=22){
            $font_size = 40;
          }
          elseif($name_len<=33){
            $font_size=40;
          }
          else {
            $font_size =50;
          }

          $certificate_text = $name;

          //font directory for name
          $drFont = "CSD-Certificates/TitilliumWeb-Regular.ttf";

         
          //function to display name on certificate picture
          $text1 = imagettftext($createimage, $font_size, $rotation, $origin_x, $origin_y, $white,$drFont, $certificate_text);

          //function to display weight name on certificate picture
          $text2 = imagettftext($createimage, $font_size_weight, $rotation, $origin1_x+2, $origin1_y, $white, $drFont, $weight);
          
           //function to display Date on certificate picture
          $text3 = imagettftext($createimage, $font_size, $rotation, $origin2_x, $origin2_y, $white, $drFont, $date);
          
            //function to display Date on certificate picture at the very bottom
          $text4 = imagettftext($createimage, $font_size, $rotation, $origin3_x, $origin3_y, $white, $drFont, $date);
          
            //function to display Date on certificate picture at the very bottom
          $text5 = imagettftext($createimage, $font_size, $rotation, $origin4_x, $origin4_y, $white, $drFont, $customerref);


          imagepng($createimage,$output,3);

 ?>

QUESTION:

Why does the PHPMailer only succeed with attaching the file after i have refreshed the page after it first fails?

Advertisement

Answer

I figured it out,

All i had to do was move the PHPMailer script BELOW the scrip that generates and saves the certificate and it worked. So obviously i was calling the mail function before the certificate was saved. so PHPMailer wasn’t able to find the file.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement