Search code examples
phppostgresqlphpmailer

"preg_match_all() expects parameter 2 to be string, resource given" Errors sending email with PHPMailer and posgresql


I am getting some errors when trying to execute a php file. This php file collects data from postgresql and sends it through a sendEmail function that is in charge of this process.

These are the 2 errors I am getting (image): enter image description here

The php code is:

<?php
$html = fopen("Status_movile_tccu.html", "w");
$cont_alarma=0;
$newline = "\r\n";



fwrite($html,'<html>'.$newline);
fwrite($html,'<head>'.$newline);
fwrite($html,'<style type="text/css">'.$newline);
fwrite($html,'  body{'.$newline);
fwrite($html,'      background-color: #F0F2F8;'.$newline);
fwrite($html,'  }'.$newline);
### ....... moore code to create html of message ...... ###
//Here comes a query
$query="SELECT pu.l2, 
            to_char(pu.d1,'YYYY-MM-DD HH24:MI:SS')d1,
            v.plate patente,e.distribuidor empresa,
            CASE WHEN pu.d1 > TO_DATE('".$fec_actual."', 'YYYY-MM-DD HH24') THEN 'AL DIA' ELSE 'ATRASADO' END AS estado 
            FROM p_ultima pu
            INNER JOIN m_users m ON m.l2=pu.l2
            INNER JOIN vehiculos v ON v.l2=m.l2
            INNER JOIN equipos e ON v.id_equipo=e.id
            WHERE m.user0=supervisor'
            ORDER BY pu.d1 DESC,e.distribuidor asc";
/* print_r($query); die(); */

    $result=pg_query($pg_conn, $query);

    fwrite($html,'<table align="center" width="80%" cellpadding="0" cellspacing="0" border="1" bordercolor="#000000" style="border-collapse:collapse; background-image:url(http://www.imagenonline.com/imagenes/205/a205236.gif); background-repeat:no-repeat; background-position:right bottom;">'.$newline);
    fwrite($html,'<tr class="tab_title2"><th colspan="4" align="center">Estatus GPS TCCU ACARREO</th></tr>'.$newline);
    fwrite($html,'<tr class="tab_title"><th>Patente</th><th>FECHA REGISTRO</th><th>EMPRESA</th><th>ESTADO</th></tr>'.$newline);
    $i=0;

This returns the array

/* test */
/* $sql=pg_fetch_array($result);
print_r($sql); die();

    Array
    (
        [0] => 87721
        [l2] => 87721
        [1] => 2021-04-14 17:55:55
        [d1] => 2021-04-14 17:55:55
        [2] => 25055765
        [patente] => 25055765
        [3] => QuecLink
        [empresa] => QuecLink
        [4] => ATRASADO
        [estado] => ATRASADO
    ) */

/* entest */



while($sql=pg_fetch_array($result)){
        $GPS=$sql['estado'];
        fwrite($html,'  <tr class="box1"><td class="boxclipat1">'.trim($sql['patente']).'</td><td class="boxclipat1">'.$sql['d1'].'</td><td class="boxclipat1">'.$sql['empresa'].'</td><td class="boxclipat1" >'.trim($GPS).'</td></tr>'.$newline);
        
    }
    fwrite($html,'</table>'.$newline);
    fwrite($html,'<table border="0" cellpadding="0" cellspacing="0" height="23" width="80%" align="center">'.$newline);
    fwrite($html,'  <tbody>'.$newline);
    fwrite($html,'          <tr>'.$newline);
    fwrite($html,'        <td class="footer" align="center">&copy; '.date('Y').' <a href="http://www.position.cl" target="_blank" style="color:#FFF">POSITION S.A.</a> | Nueva Tajamar 481, Torre Norte, Of. 802. Santiago. Chile | Tel&eacute;fono (562)2318283 - FAX (562)2320871</td>'.$newline);
    fwrite($html,'        </tr>'.$newline);
    fwrite($html,'    </tbody>'.$newline);
    fwrite($html,'</table>'.$newline);
    
    fwrite($html,'</body>'.$newline);
    fwrite($html,'</html>');
    fclose($html);

Here comes the email sending

$subject = "Status Report Customer ".$fec_actual."";
$emails=getReportEmailsWithBcc($pg_conn, '', '', 216); //get emails from database
/* print_r($emails);die(); */
$clientEmails=$emails['mail_list'];
$companyEmails = $emails['bcc_list'];
$attachment='';

//Send parameters through sentEmailsReport function
    sentEmailsReport($subject, $clientEmails, $companyEmails, $html, $attachment)

And last step

function sentEmailsReport($subject, $clientEmails, $companyEmails, $bodyHtml, $attachment)
{
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->SMTPAuth = false;
    $mail->Host       = "mx.gtdinternet.com";
    $mail->Port       = 25;
    $mail->Username   = "[email protected]";
    $mail->Password   = "inf0.114";            // GMAIL password
    $mail->AddReplyTo("[email protected]", "COMPANY");
    $mail->From       = "[email protected]";
    $mail->FromName   = "COMPANY- REPORTE";
    $mail->Subject    = $subject;
    $mail->AltBody    = "Para poder ver este mensaje correctamente, debe utilizar un cliente mail con HTML compatible."; // optional, comment out and test
    $mail->WordWrap   = 50; // set word wrap
    $mail->MsgHTML($bodyHtml);

    if (!is_null($attachment)) {
        $mail->AddAttachment($attachment);
    }

    if (trim($clientEmails) != "") {
        $client = explode(",", $clientEmails);
        for ($k = 0; $k < count($client); $k++) {
            $mail->AddAddress($client[$k]);
        }
    }

    $company = explode(",", $companyEmails);
    for ($k = 0; $k < count($company); $k++) {
        $mail->AddBCC($company[$k]);
    }

    $mail->IsHTML(true); // send as HTML

    if (!$mail->Send()) {
        echo "error " . $mail->ErrorInfo;
        return false;
    }else{
        echo 'Mail enviado - ok'. PHP_EOL;
    }

    return true;
}

after I excecuted this php, Is returned the mentioned errors and also I receive this email enter image description here


Solution

  •  $mail->MsgHTML($bodyHtml)
    

    For the parameter $bodyHtml, you passed $html into your function:

     //Send parameters through sentEmailsReport function
     sentEmailsReport($subject, $clientEmails, $companyEmails, $html, $attachment);
    

    And that indeed appears to be a resource,

    $html = fopen("Status_movile_tccu.html", "w");
    

    So you will need to read the content of that file, and pass that string value into the function instead:

    $bodyContent = file_get_contents("Status_movile_tccu.html");
    sentEmailsReport($subject, $clientEmails, $companyEmails, $bodyContent, $attachment);
    

    Edit: This previously was file_get_contents($html);, which is of course not correct here, because that function wants the path to a file as first parameter, not an opened file resource. Fixed in above code.