Как отправить несколько электронных писем, содержащих PDF с TCPDF - PullRequest
0 голосов
/ 21 сентября 2018

Я пытаюсь отправить многочисленные электронные письма с вложениями в формате PDF, используя CURL и TCPDF.

Я делаю MySql Выберите, чтобы получить необходимую информацию, и я пытаюсь использовать CURL, чтобы передать переменную в мой TCPDF файл.

Запрос SELECT, выполняющийся на Cronjob в Cpanel

$stmt = $conn->prepare("
    SELECT sID
    FROM School_Schedule 
    LEFT JOIN Schools ON School_Schedule.School = Schools.s_ID 
    WHERE Date_Schedule = (CURDATE() - INTERVAL 2 DAY)
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $SchoolId = $row["sID"];
    $post = ['SchoolId' => $SchoolId];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.test.com.au/secure/TCPDF-master/s/schoolList.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    $response = curl_exec($ch);
    var_export($response);
    //header("Location:../secure/TCPDF-master/s/schoolList.php?school=" . $SchoolId . "");
    //foreach($post as $SchoolId){
    //    header("Location:../secure/TCPDF-master/s/schoolList.php?school=" . $SchoolId . "");
    //}
}

В TCPDF я получаю переменную:

$SchoolId = $_GET['SchoolId'];

Затем элемент Select внутри TCPDF

SELECT RefNr, SchoolName, ChildInitials, SchoolEmail, Date_issued FROM Ref 
LEFT JOIN School_Schedule ON School_Schedule.SchoolList = Ref.Schools
LEFT JOIN Schools ON Schools.sc_ID = Ref.Schools
WHERE Schools.sID = $SchoolId

А затем остальная часть обычного кода TCPDF.

Я проверил операторы SQL в phpMyAdmin, и они работают.Я проверил TCPDF с жестко закодированными значениями, и код работает.

Я пробовал верхний блок кода с двумя строками, который закомментирован (заголовок и foreach), но не работал.

По не работал я имею ввиду, что письмо (я) не отправлено скриптом.В консоли не регистрируются ошибки.

Я подозреваю, что неэффективно использую CURL.Это мое первое использование.

** РЕДАКТИРОВАТЬ: ** Ниже код TCPDF

<?php

$SchoolId = $_GET['SchoolId'];

require_once('tcpdf_include.php');

require_once('../../connect.php');

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, 'LETTER', true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Identykidz');
$pdf->SetTitle('Identykidz Child Identity Kit');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' ', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set certificate file
$certificate = 'file://data/cert/tcpdf.crt';

// set additional information
$info = array(
'Name' => 'Name',
'Location' => 'My Address',
'Reason' => 'Reason',
'ContactInfo' => 'https://www.test.com.au',
);

// set document signature
$pdf->setSignature($certificate, $certificate, 'tcpdfdemo', '', 2, $info);

// set font
$pdf->SetFont('helvetica', 'B', 7);

// add a page
$pdf->AddPage();
//output the HTML content
$tbl_header = '<table border="1" bordercolor=”grey”>';
$tbl_footer = '</table>';
$text ='';

// print a line of text
$findSchoolList = $conn->prepare("SELECT RefNr, SchoolName, ChildInitials, SchoolEmail, Date_issued FROM Ref 
LEFT JOIN School_Schedule ON School_Schedule.SchoolList = Ref.Schools
LEFT JOIN Schools ON Schools.sc_ID = Ref.Schools
WHERE Schools.sID = $SchoolId");
$findSchoolList->execute();

while ($result = $findSchoolList->fetch(PDO::FETCH_ASSOC)){
$RefNr= htmlentities($result['RefNr']);
$SchoolName = htmlentities($result['SchoolName']);
$ChildInitials = htmlentities($result['ChildInitials']);
$SchoolEmail = htmlentities($result['SchoolEmail']);    
$Date_issued= htmlentities($result['Date_issued']);


 $text .= '<tr><td>' . $UniqueRefNr . '</td><td>' . $ChildInitials . '</td><td>' . $School . '</td></tr>';


 }

$pdf->writeHTML($tbl_header . $text . $tbl_footer, true, false, false, false, '');

$pdf->setSignatureAppearance(180, 60, 15, 15);

$pdf->addEmptySignatureAppearance(180, 80, 15, 15);

$to = $SchoolEmail;
$subject = $School;
$repEmail = 'info@test.com.au';

$fileName = 'FileName.pdf';
$fileatt = $pdf->Output($fileName, 'S');
$attachment = chunk_split(base64_encode($fileatt));
$eol = PHP_EOL;
$separator = md5(time());

$headers = 'From: Test <'.$repEmail.'>'.$eol;
$headers .= 'MIME-Version: 1.0' .$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";

$message = "--".$separator.$eol;
$message .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$message .= "Dear parent.  \r\n\r\nPlease find attached list as requested.\r\n".$eol;

$message .= "--".$separator.$eol;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$message .= "Content-Transfer-Encoding: 8bit".$eol.$eol;

$message .= "--".$separator.$eol;
$message .= "Content-Type: application/pdf; name=\"".$fileName."\"".$eol; 

$message .= "Content-Transfer-Encoding: base64".$eol;
$message .= "Content-Disposition: attachment".$eol.$eol;
$message .= $attachment.$eol;
$message .= "--".$separator."--";

// Send the email
if(mail($to, $subject, $message, $headers)) {
  echo "Sent";
}
else {

  echo "There was an error sending the mail.";
}
exit;
//============================================================+
// END OF FILE
//============================================================+

1 Ответ

0 голосов
/ 21 сентября 2018

Вы отправляете запрос POST с curl и добавляете параметры с

$post = ['SchoolId' => $SchoolId]; curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));.

Но в вашем файле TCPDF вы используете $SchoolId = $_GET['school'];, который всегда будетбыть пустым, поскольку это POST, а не GET запрос.

Чтобы устранить проблему, замените $_GET['school']; на $_POST['SchoolId'];, поскольку вы отправляете параметр с именем SchoolId, а не school

...