TCPDF: вложение PHPMailer пусто - PullRequest
3 голосов
/ 18 февраля 2020

Я использую TCPDF для создания профиля и отправки профиля в виде вложения. У меня много клиентов, использующих программное обеспечение, и возникла необходимость в массовом почтовом обслуживании.

Я отправлял профиль с локального сервера электронной почты, и он отлично работал.

Вот предыдущий код (только часть электронной почты):

$pdf->writeHTML($tbl, true, false, false, false, '');

$js .= 'print(true);';
// set javascript

$pdf->IncludeJS($js); 

//Close and output PDF document

//Close and output PDF document

//define the receiver of the email
$to = $Email;
$subject = "Profile";
$repEmail = 'me@mydomain.com';

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

$headers = 'From: Identykidz <'.$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/guardian  \r\n\r\nPlease find attached the Profile attached.Kind regards\r\nIdentyKidz Information Centre".$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 '<span style="color:#1e73be; text-align: center; font-family: Verdana">The profile has been sent successfully to the email address entered.</span>';
}
else {

echo "There was an error sending the mail.";
}
}
//catch exception
catch(Exception $e) {
header("Location: something_went_wrong.php");
}

//============================================================+
// END OF FILE
//============================================================+

Поскольку мне нужно использовать службу массовой рассылки, я должен включить SMTP-детали поставщика службы массовой рассылки, поэтому я изменил часть электронной почты TCPDF на PHPMailer с mail ().

Вот новая часть электронной почты кода TCPDF:

$pdf->writeHTML($tbl, true, false, false, false, '');

$js .= 'print(true);';

// set javascript
$pdf->IncludeJS($js); 

$fileatt = $pdf->Output('Profile.pdf', 'S');
//I have also tried $fileatt = $pdf->Output('Profile.pdf', 'I');

require ('PHPMailer/PHPMailerAutoload.php');

$pdf_content = file_get_contents($fileatt);

$sender = 'Me@mydomain.com';
$senderName = 'Information Centre';

// Replace recipient@example.com with a "To" address. If your account
// is still in the sandbox, this address must be verified.
$recipient = $Email;

// Replace smtp_username with your Amazon SES SMTP user name.
$usernameSmtp = 'Mycredentials';

// Replace smtp_password with your Amazon SES SMTP password.
$passwordSmtp = 'Mycredentials';

 // Specify a configuration set. If you do not want to use a configuration
// set, comment or remove the next line.
//$configurationSet = 'ConfigSet';

// If you're using Amazon SES in a region other than US West (Oregon),
// replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP
// endpoint in the appropriate region.
$host = 'email-smtp.eu-central-1.com';
$port = 587;

// The subject line of the email
$subject = "IdentyKidz Profile of $name";

// The plain-text body of the email
$bodyText =  "";

// The HTML-formatted body of the email
$bodyHtml = "Dear parent/guardian <br><br>
Kind regards<br>IdentyKidz Information Centre";

$mail = new PHPMailer(true);

try {
    // Specify the SMTP settings.
$mail->isSMTP();
$mail->setFrom($sender, $senderName);
$mail->Username   = $usernameSmtp;
$mail->Password   = $passwordSmtp;
$mail->Host       = $host;
$mail->Port       = $port;
$mail->SMTPAuth   = true;
$mail->SMTPSecure = 'tls';
$mail->addCustomHeader('X-SES-CONFIGURATION-SET', $configurationSet);

// Specify the message recipients.
$mail->addAddress($recipient);
// You can also add CC, BCC, and additional To recipients here.

// Specify the content of the message.
$mail->isHTML(true);
$mail->Subject    = $subject;
$mail->Body       = $bodyHtml;
$mail->AltBody    = $bodyText;
$mail->AddStringAttachment($pdf_content, "Prodile.pdf", "base64", "application/pdf");

// Send the email
if($mail->Send()) {
echo '<span style="color:#1e73be; text-align: center; font-family: Verdana">The profile has been sent successfully to the email address entered.</span>';
}
else {

echo "There was an error sending the mail.";
}

} catch (phpmailerException $e) {
echo "An error occurred. {$e->errorMessage()}", PHP_EOL; //Catch errors from PHPMailer.
} catch (Exception $e) {
echo "Email not sent. {$mail->ErrorInfo}", PHP_EOL; //Catch errors from Amazon SES.
}

}
//catch exception
catch(Exception $e) {
header("Location: something_went_wrong.php");
}

//============================================================+
// END OF FILE
//============================================================+

Второй код (PHP Mailer) отправляет электронное письмо, но, но и указывает, что PDF прикреплен, но вложение пусто.

Чего мне не хватает?

Ответы [ 5 ]

3 голосов
/ 25 февраля 2020

Здравствуйте, CharlesWaschington, я проверил ваши примеры кода:

В соответствии с вашим кодом я увидел, что вы пытаетесь загрузить файл из строки.

Это немного озадачивает меня, потому что я сразу получил ошибку. Вы включили error_reporting и error_log и проверили свои логи? В любом случае вам нужно только поместить строку в правильную переменную, и все остальное работает. Ниже вы найдете мои изменения в вашем коде.

До:

$fileatt = $pdf->Output('Profile.pdf', 'S'); // S = Means return the PDF as string
// ... code ... 
$pdf_content = file_get_contents($fileatt);
// .. code
$mail->AddStringAttachment($pdf_content, "Prodile.pdf", "base64", "application/pdf");

После:

$pdf_content = $pdf->Output('Profile.pdf', 'S'); 
// ... code ... 
$mail->AddStringAttachment($pdf_content, "Prodile.pdf", "base64", "application/pdf");

Я только что проверил ваш скрипт с учетными данными SES и пользовательский PDF, а также ранее созданный PDF.

Дайте мне знать, если это поможет.

2 голосов
/ 28 февраля 2020

Используя

$fileatt = $pdf->Output('Profile.pdf', 'S');
//I have also tried $fileatt = $pdf->Output('Profile.pdf', 'I');

require ('PHPMailer/PHPMailerAutoload.php');

$pdf_content = file_get_contents($fileatt);

Вы пытаетесь прочитать file_content из строки.

Вы можете просто отправить вложение по

 $mail->AddStringAttachment($fileatt, "Prodile.pdf", "base64", "application/pdf");  
1 голос
/ 21 февраля 2020

Я думаю, может быть, вам нужно base64_decode вложение. См. здесь , первый ответ:

$mail->AddStringAttachment(base64_decode($pdf_content), "Prodile.pdf", "base64", "application/pdf");

* 301 * 3-й параметр AddStringAttachment только сообщает кодировку , но, по-видимому, не выполняет никакой кодировки для вас .

0 голосов
/ 28 февраля 2020

Мне удалось разобрать проблему согласно комментарию ivion.

$mail->AddStringAttachment($fileatt, "Prodile.pdf", "base64", "application/pdf");

0 голосов
/ 27 февраля 2020

Попробуйте этот метод

$mail->AllowEmpty = true;
...