mail(): headers parameter must be string or array in /home/acifinan/public_html/application.php on line 40

gcozba2023

New member
Hi Team

I need some help, i am not getting any luck to get an email with an attached pdf
Code:
// Email settings 
$toEmail = 'Ongeziwe.Gogotya@agilelimitless.org.za'; // Recipient email 
$from = 'gcobani.mkontwana@agilelimitless.org.za'; // Sender email 
$fromName = 'Agile Limiteless Development'; // Sender name 
 
// File upload settings 
$attachmentUploadDir = "uploads/"; 
$allowFileTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg'); 
 
 
/* Form submission handler code */ 
$postData = $uploadedFile = $statusMsg = $valErr = ''; 
$msgClass = 'errordiv'; 
if(isset($_POST['button'])){ 
    // Get the submitted form data 
    $amount = trim($_POST['amount']); 
    $purpose = trim($_POST['purpose']); 
    $voucher = trim($_POST['voucher']); 
    $gender = trim($_POST['gender']); 
	$fname = trim($_POST['fname']);
	$lname = trim($_POST['lname']);
	$title = trim($_POST['title']);
	$typeID = trim($_POST['typeID']);
	$email = trim($_POST['email']);
	$number = trim($_POST['number']);
	$maritalstatus = trim($_POST['maritalstatus']);
	$street1 = trim($_POST['stree1']);
	$street2 = trim($_POST['street2']);
	$town = trim($_POST['town']);
	$provice = trim($_POST['provice']);
	$code = trim($_POST['code']);
	$propertyownership = trim($_POST['propertyownership']);
	$placeofwork = trim($_POST['placeofwork']);
	$jobtitle = trim($_POST['jobtitle']);
	$jobstreet = trim($_POST['jobstreet']);
	$jobstreet2 = trim($_POST['jobstreet2']);
	$worknumber = trim($_POST['worknumber']);
	$jobtown = trim($_POST['jobtown']);
	$jobprovince = trim($_POST['']);
	$jobcode = trim($_POST['jobcode']);
	$income = trim($_POST['income']);
	$bankname = trim($_POST['bankname']);
	$branchname = trim($_POST['branchname']);
	$accountno = trim($_POST['accountno']);
	$accounttype = trim($_POST['accounttype']);
	$signature = trim($_POST['signature']);
	$id = trim($_POST['id']);
	$bankstatement = trim($_POST['bankstatement']);
	$payslip = trim($_POST['payslip']);
 
   
    // Check whether submitted data is valid 
    if(empty($valErr)){ 
        $uploadStatus = 1; 
         
        // Upload attachment file 
        if(!empty($_FILES["bankstatement"]["name"])){ 
             
            // File path config 
            $targetDir = $attachmentUploadDir; 
            $fileName = basename($_FILES["bankstatement"]["name"]); 
            $targetFilePath = $targetDir . $fileName; 
            $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); 
             
            // Allow certain file formats 
            if(in_array($fileType, $allowFileTypes)){ 
                // Upload file to the server 
                if(move_uploaded_file($_FILES["bankstatement"]["tmp_name"], $targetFilePath)){ 
                    $uploadedFile = $targetFilePath; 
                }else{ 
                    $uploadStatus = 0; 
                    $statusMsg = "Sorry, there was an error uploading your file."; 
                } 
            }else{ 
                $uploadStatus = 0; 
                $statusMsg = 'Sorry, only '.implode('/', $allowFileTypes).' files are allowed to upload.'; 
            } 
        } 
         
        if($uploadStatus == 1){ 
            // Email subject 
            $emailSubject = 'Contact Request Submitted by '.$name; 
             
            // Email message  
            $htmlContent = '<h2>Contact Request Submitted</h2> 
                <p><b>Name:</b> '.$name.'</p> 
                <p><b>Email:</b> '.$email.'</p> 
                <p><b>Subject:</b> '.$subject.'</p> 
                <p><b>Message:</b><br/>'.$message.'</p>'; 
             
            // Header for sender info 
            $headers = "From: $fromName"." <".$from.">"; 
 
            // Add attachment to email 
            if(!empty($uploadedFile) && file_exists($uploadedFile)){ 
                 
                // Boundary  
                $semi_rand = md5(time());  
                $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";  
                 
                // Headers for attachment  
                $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";  
                 
                // Multipart boundary  
                $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" . 
                "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";  
                 
                // Preparing attachment 
                if(is_file($uploadedFile)){ 
                    $message .= "--{$mime_boundary}\n"; 
                    $fp =    @fopen($uploadedFile,"rb"); 
                    $data =  @fread($fp,filesize($uploadedFile)); 
                    @fclose($fp); 
                    $data = chunk_split(base64_encode($data)); 
                    $message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .  
                    "Content-Description: ".basename($uploadedFile)."\n" . 
                    "Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .  
                    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 
                } 
                 
                $message .= "--{$mime_boundary}--"; 
                $returnpath = "-f" . $email; 
                 
                // Send email 
                $mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath); 
                 
                // Delete attachment file from the server 
                @unlink($uploadedFile); 
            }else{ 
                    // Set content-type header for sending HTML email 
                $headers .= "\r\n". "MIME-Version: 1.0"; 
                $headers .= "\r\n". "Content-type:text/html;charset=UTF-8"; 
                 
                // Send email 
                $mail = mail($toEmail, $emailSubject, $htmlContent, $headers);  
            } 
             
            // If mail sent 
            if($mail){ 
                $statusMsg = 'Thanks! Your contact request has been submitted successfully.'; 
                $msgClass = 'succdiv'; 
                 
                $postData = ''; 
            }else{ 
                $statusMsg = 'Failed! Something went wrong, please try again.'; 
            } 
        } 
    }else{ 
        $valErr = !empty($valErr)?'<br/>'.trim($valErr, '<br/>'):''; 
        $statusMsg = 'Please fill all the mandatory fields.'.$valErr; 
    }
    
} 
echo  'finnaly';
?>
// application.php
Code:
 require_once 'send-email-attachment.php';
    
    $logo = 'assets/img/logo.png';
    $link = 'https://acifinance.co.za/';
	$body = "<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><title>ACI Finance</title></head><body>";
	$body .= "<table style='width: 100%;'>";
	$body .= "<thead style='text-align: center;'><tr><td style='border:none;' colspan='2'>";
	$body .= "<a href='{$link}'><img src='{$logo}' alt=''></a><br><br>";
	$body .= "</td></tr></thead><tbody><tr>";
	$body .= "<td style='border:none;'><strong>Name:</strong> {$fname} {$lname}</td>";
	$body .= "<td style='border:none;'><strong>Email:</strong> {$from}</td>";
	$body .= "</tr>";
	$body .= "<tr><td style='border:none;'><strong>CellNumber:</strong> {$number}</td></tr>";
	$body .= "<tr><td></td></tr>";
	$body .= "<tr><td style='border:none;'><strong>Loan Amount:</strong> {$amount}</td></tr>";
	$body .= "<tr><td></td></tr>";
	$body .= "<tr><td style='border:none;'><strong>Monthly income:</strong> {$income}</td></tr>";
	$body .= "<tr><td></td></tr>";
	$body .= "<tr><td style='border:none;'><strong>Town:</strong> {$town}</td></tr>";
	$body .= "<tr><td></td></tr>";
	$body .= "<tr><td style='border:none;'><strong>Upload bankstatement </strong> {$bankstatement}</td></tr>";
	$body .= "<tr><td></td></tr>";
	$body .= "<tr><td style='border:none;'><strong>Upload payslip:</strong> {$payslip}</td></tr>";
	$body .= "<tr><td></td></tr>";
	$body .= "<tr><td colspan='2' style='border:none;'><strong></strong> </td></tr>";
	// attachment
 $body .= "--" . $separator . $eol;
 $body .= "Content-Type: application/pdf; name=\"" . $fileName . "\"" . $eol;
 $body .= "Content-Transfer-Encoding: base64" . $eol;
 $body .= "Content-Disposition: attachment" . $eol;
 $body .= $content . $eol;
 $body .= "--" . $separator . "--";
	$body .= "</tbody></table>";
	
$body .= "</body></html>";
	

    $send = mail($to, $subject, $body, $headers); 
    echo$headers;
    
   $amount  =$_POST['amount'];
   $purpose =$_POST['purpose'];
   $voucher =$_POST['voucher'];
   $gender =$_POST['gender'];
$bankstatement=$_POST[bankstatement];
   // Connect to database
   
   $conn = new mysqli('localhost','acifinan_acifinan','Finance_01','acifinan_acifinanc');
   if ($conn->connect_error)
   {die('Connection Failed:'.$conn-> connect_error); }
   else 
  {
      $stmt= $conn->prepare("insert into application(amount, purpose, voucher, gender, fname, lname, title, typeID, email, number, maritalstatus, street1, street2, town, province, code, propertyownership, placeofwork, jobtitle, jobstreet, jobstreet2, jobtown, worknumber, jobprovince, jobcode, income, bankname, branchname, accountno, accounttype, signature, id, bankstatement, payslip) values (? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)");
      $stmt-> bind_param("ssssssssssssssssssssssssssssssssss" , $amount,$purpose,$voucher,$gender,$fname,$lname,$title,$typeID,$email,$number,$maritalstatus,$street1,$street2,$town,$province,$code,$propertyownership,$placeofwork,$jobtitle,$jobstreet,$jobstreet2,$jobtown,$worknumber,$jobprovince,$jobcode,$income,$bankname,$branchname,$accountno,$accounttype,$signature,$id,$bankstatement,$payslip);
      $stmt->execute();
      echo "Submitted Successfully";
      $stmt->close();
      $conn->close();
 
Did you consider ro use phpmailer or other package to sendi g the emails?
You are declaring the $header variable only when you have uploaded file otherwise the $header is undefined.
Please also consider sending emails from the queue instead directly while the request
 
Michalio said:
Did you consider ro use phpmailer or other package to sendi g the emails?
You are declaring the $header variable only when you have uploaded file otherwise the $header is undefined.
Please also consider sending emails from the queue instead directly while the request

Yes and made some changes with the code to send-email attachment, but now its complaining about the path according to the logs and dont know how to fix that.

Code:
<?php

require '..\_lib\vendor\phpmailer\phpmailer'; // this line of code and do have this path
"PHP Fatal error:  require(): Failed opening required '..\_lib\vendor\phpmailer\phpmailer' (include_path='.:/opt/cpanel/ea-php73/root/usr/share/pear') in /home/acifinan/public_html/send-email-attachment.php on line 3"
use PHPMailer\PHPMailer;



$msg = '';
if (array_key_exists('bankstatement', $_FILES)) {
    //Create a message
    $mail = new PHPMailer();
    $mail->setFrom('info@acifinance', 'ACI Finance');
    $mail->addAddress('gcobani.mkontwana@agilelimitless.org.za', 'ACI Finance');
    $mail->Subject = 'ACI Finance Application Loan';
    $mail->Body = 'My message body';
    //Attach multiple files one by one
    for ($ct = 0, $ctMax = count($_FILES['bankstatement']['tmp_name']); $ct < $ctMax; $ct++) {
        //Extract an extension from the provided filename
        $ext = PHPMailer::mb_pathinfo($_FILES['bankstatement']['name'][$ct], PATHINFO_EXTENSION);
        //Define a safe location to move the uploaded file to, preserving the extension
        $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['bankstatement']['name'][$ct])) . '.' . $ext;
        $filename = $_FILES['bankstatement']['name'][$ct];
        if (move_uploaded_file($_FILES['bankstatement']['tmp_name'][$ct], $uploadfile)) {
            if (!$mail->addAttachment($uploadfile, $filename)) {
                $msg .= 'Failed to attach file ' . $filename;
            }
        } else {
            $msg .= 'Failed to move file to ' . $uploadfile;
        }
    }
    if (!$mail->send()) {
        $msg .= 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        $msg .= 'Message sent!';
    }
}
?>
 
Back
Top