I am sending email with PHPMailer. My email design is available in the template.php file. I am pulling the contents of the template.php file with the file_get_contents method in my mail.php file. But I have such a problem, all my php codes in the template.php file are also visible. How can I hide them?
Mail.php
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require_once 'assets/standart/db.php';
require 'assets/class/all.php';
$connect = new baglan();
$settings = new ayarlar();
// SMTP settings connect
$connect->connect('settings_smtp', '', '', 0);
$smtp_settings = $connect->connect->fetch(PDO::FETCH_ASSOC);
$smtp_mail = $smtp_settings['mail'];
// /SMTP settings connect
$template_file = 'PHPMailer/template.php';
if(file_exists($template_file)){
$mail_template = htmlspecialchars(file_get_contents($template_file));
}else{
die("Unable to locate the template file");
}
//Load Composer's autoloader
// require 'vendor/autoload.php';
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = $smtp_settings['host'];
$mail->SMTPAuth = true;
$mail->Username = $smtp_settings['mail'];
$mail->Password = $smtp_settings['password'];
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = $smtp_settings['port'];
//Recipients
$mail->setFrom("$smtp_mail", 'Mailer');
$mail->addAddress('example#gmail.com', 'Joe User'); //Add a recipient
// $mail->addAddress('ellen#example.com'); //Name is optional
// $mail->addReplyTo('info#example.com', 'Information');
// $mail->addCC('cc#example.com');
// $mail->addBCC('bcc#example.com');
//Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name
//Content
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Subject = 'Here is the subject';
$mail->Body = $mail_template;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Template.php
<?php
echo $forexample = 'Some words here';
?>
Don’t use file_get_contents for that, use include with output buffering. That way it will run the PHP code and you’ll see the results of its execution instead of the code itself.
You have to run the template file, not simply read it.
You can do that like this:
ob_start();
include ( $template_file );
$mail_template = ob_get_clean();
ob_start() (output-buffer start) causes all php script output (from echo etc) to go into an output buffer. output_get_clean() retrieves that output.
With
$mail_template = htmlspecialchars(file_get_contents($template_file));
you will just get the contents of the file into the variable $mail_template
You could use the eval() function as described here: https://www.php.net/manual/en/function.eval.php
But be very careful using it!
Caution: The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
You could use it like this:
$mail_template_php = htmlspecialchars(file_get_contents($template_file));
$mail_template = eval($mail_template_php);
Related
Good morning all ,
I would like to attach a PDF created following a form with HTML2PDF then send it with PHMailer.
Everything works, the email goes well, I managed to create the PDF by saving it on my hard drive.
But when I try to attach it to my email, the pdf is fine in pj but I can't open it.
enter image description here
It is the same size of my locally created pdf.
I followed the tutorial and wiki of the two libraries, well I think ^^
Here is my PHPMailer code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require './vendor/phpmailer/phpmailer/src/Exception.php';
require './vendor/phpmailer/phpmailer/src/PHPMailer.php';
require './vendor/phpmailer/phpmailer/src/SMTP.php';
require './vendor/autoload.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = '******'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '*****'; // SMTP username
$mail->Password = '*****'; // SMTP password
//$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = ****; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('****#****.com', '****');
$mail->addAddress($to); // Add a recipient
//$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo($shop_email, 'Votre magasin');
//$mail->addCC('cc#example.com');
$mail->addBCC($shop_email);
// Attachments
$mail->addStringAttachment($pdf_done, 'myPdf.pdf'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = strip_tags($message);
$mail->send();
echo '';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
and here is the code for HTML2PDF:
ob_start();
// --> mon code HTML de creeation du PDF
$content = ob_get_clean();
require_once dirname(__FILE__).'/../vendor/autoload.php';
use Spipu\Html2Pdf\Html2Pdf;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use Spipu\Html2Pdf\Exception\ExceptionFormatter;
try{
$pdf = new \Spipu\Html2Pdf\Html2Pdf('P', 'A4', 'fr');
$pdf->writeHTML($content);
$pdf_done = $pdf->output('myPdf.pdf', 'S');
}catch(\Spipu\Html2Pdf\Exception\Html2PdfException $e){
die($e);
}
?>
I tried adding ", 'base64', 'application / pdf'" in the addStringAttachment but it doesn't change anything.
Do you have any idea of my mistake?
Thank you all
Debug one thing at a time. First download the PDF manually and make sure it looks correct – if the PDF is bad to start with, emailing it isn't going to improve things. Next check that it is readable from PHP – for example serve it using readfile(). Then when you try to attach it, check the return value of your call to addAttachment() like this:
if (!$mail->addAttachment('/path/to/myPdf.pdf')) {
die('could not read PDF');
}
Also note the difference between addAttachment and addStringAttachment; you're adding a file that's been saved to disk, so you want the first one, not the second.
I have a simple php file that sends an email using PHPMailer. It works great when run from the browser.
When I try to run it from a cron job I don't get the email. I have looked for quite a while for an answer here, but I have not been able to get it to work.
Most solution have to do with relative paths in the php code. I changed the paths on the require lines to be absolute if cron job has a different path.
I am pretty new to all of this, so any help would be appreciated.
I am probably missing something simple.
Thanks in advance for your help.
<?php
/* Namespace alias. */
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
/* If you installed PHPMailer without Composer do this instead: */
require '/hermes/bosnaweb21a/b1837/ipw.whitmerd/public_html/test03/include/PHPMailer/PHPMailer.php';
require '/hermes/bosnaweb21a/b1837/ipw.whitmerd/public_html/test03/include/PHPMailer/Exception.php';
require '/hermes/bosnaweb21a/b1837/ipw.whitmerd/public_html/test03/include/PHPMailer/SMTP.php';
//SMTP needs accurate times, and the PHP time zone MUST be set
date_default_timezone_set('America/New_York');
echo phpinfo();
echo __DIR__;
// Email the results
$mailSubject = "Email Subject";
// Create the body of the mail
$mailBody = "Body of email";
/* Create a new PHPMailer object. Passing TRUE to the constructor enables exceptions. */
$mail = new PHPMailer(TRUE);
// Configure the mail object for iPower email account
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->Host = "smtp.ipower.com";
$mail->Port = 25;
$mail->SMTPSecure = 'tls';
$mail->isHtml(true);
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->Username = "validuser";
$mail->Password = "password";
$mail->setFrom('Example#gmail.com', 'Example Name');
$mail->Subject = $mailSubject;
$mail->addAddress('Example#gmail.com', 'Example Name');
$mail->Body = $mailBody;
$mailSendSuccess = $mail->send();
$mail = null;
// Success or failure message
if ($mailSendSuccess) {
echo "<br>Email was sent sucessfully.";
} else {
echo "<br>There was a problem sending the email.";
}
I wanted to get the phpinfo() information with the job running from cron job. So I was trying to create a file in a know location.
I tried this simple file operation that works well from the browser, but not from the cron job.
I commented out the code to grab the phpinfo into a file to just create a dummy file and that is not working.
<?php
$tempDir = '/hermes/bosnaweb21a/b1837/ipw.whitmerd/public_html/test03/misc/';
$tempFile = 'phpini_fromcron.html';
$fileContents = dirname(__DIR__);
$fileContents .= '<br>';
$fileContents .= 'Test file contents.';
// ob_start();
// phpinfo();
// $phpini = ob_get_contents();
// ob_end_clean();
// $fileContents .= $phpini;
$createFile = fopen($tempDir . $tempFile, 'w');
if (fwrite($createFile, $fileContents)) {
echo "File created.";
} else {
echo "There were problems.";
}
fclose($createFile);
Solved, kinda?
Turns out the directory name was the problem. I don't know what, as the permissions are set the same.
If anyone has a theory as to why, I would love to hear it.
I would like to use PHPMailer in my MVC site but the view content doesn't come for the $emailTemplate variable. This is my own MVC. The problem starts here:
$emailTemplate = $this->view('emails/expirityRemainder'); Could somebody tell me how to manage that change?
If I will do that everything works fine, but I need to load different views:
$emailTemplate = 'The email body';
Here is my controller:
<?php
class Emails extends Controller{
//Send email to remamber the expirity date
public function sendReinder($data){
$emailTemplate = $this->view('emails/expirityRemainder');
$data=[
'recipient'=>'anEmail#yahoo.com',
'subject'=>'TheSubject',
'htmlBody'=>$emailTemplate,
'nonHtmlBody'=>'This is the body in plain text for non-HTML mail clients',
'sentMessage'=>'Message has been sent'
];
$email = new Email();
$email->sendMail($data);
}
}
The 'expirityRemainder.php' file contains a text:
Here will be the HTML code formatted
The PHPMailer file is inside of that libraries/PHPMailer folder.
The Email class send the email (on my server the below blank details are filled):
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
class Email{
public function sendMail($data){
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup SMTP servers smtp.topwebdeveloper.co.uk
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to 465 25 587
//Recipients
$mail->setFrom('', '');
//$mail->addAddress('', ''); // Add a recipient
//$mail->addAddress(''); // Name is optional
$mail->addAddress($data['recipient'], 'Nameee');
$mail->addReplyTo('', 'Information');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = $data['htmlBody'];
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
print_r($data);
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
print_r($data);
}
}
}
?>
This is the output:
Here will be the html code formatted
Message could not be sent.
Mailer Error: Message body emptyArray ( [recipient] => anEmail#yahoo.com [subject] => TheSubject [htmlBody] => [nonHtmlBody] => This is the body in plain text for non-HTML mail clients [sentMessage] => Message has been sent )`
I think the view content is expected to not be a string... The $data['htmlBody']inside if sendMail($data) did not receive the view content.
The view method works perfect for my MVC, except that situation when I try to load an mail text:
<?php
class Controller{
public function model($model){
require_once '../app/models/'.$model.'.php';
return new $model();
}
public function view($view, $data=[]){
if(file_exists('../app/views/'.$view.'.php')){
require_once '../app/views/'.$view.'.php';
} else {
die('vien not exists');
}
}
}
I created a new method but still not working:
<?php
public function loadEmailView($view, $data=[]){
if(file_exists('../app/views/'.$view.'.php')){
//ob_start();
//include('../app/views/'.$view.'.php');
//$file = ob_end_flush();
//echo file_get_contents('../app/views/'.$view.'.php');
//$data['htmlBody'] = require_once '../app/views/'.$view.'.php';
} else {
die('Email vien not exists');
}
}
None of the 3 above solutions not add the view content to my htmlBody variable:
<?php
class Emails extends Controller{
//Send email to remamber the expirity date
public function sendReinder($data){
$emailTemplate = $this->loadEmailView('emails/expirityRemainder');
//$emailTemplate = file_get_contents('email_template.php');
$data=[
'recipient'=>'anEmail#yahoo.com',
'subject'=>'TheSubject',
'htmlBody'=>$emailTemplate,
'nonHtmlBody'=>'This is the body in plain text for non-HTML mail clients',
'sentMessage'=>'Message has been sent'
];
$email = new Email();
$email->sendMail($data);
}
}
Thank you!
I have managed to generate pdf from my HTML page but unable to send the pdf as an attachment using phpmailer. Please, see my code below. What am I missing?
Key points:
The html(tractpage2.php) renders well to PDF
PHPmailer works but it only sends the $message without the attachment.
Problem is that the pdf does not attach the mail
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';
//reference the dompdf namescape
use Dompdf\Dompdf;
//initialise dompdf class
// get/setup the htmlpage
ob_start();
require("tractpage2.php"); // The html document
$page = ob_get_contents();
ob_end_clean();
// convert to pdf
$document = new Dompdf();
$document->set_option('defaultFont', 'Courier');
$document->load_html($page);
// set paper orientation
$document->set_paper('A4', 'portrait');
// Render the HTML as PDF
$document->render();
// Output the generated PDF to Browser
$document->stream("contract.pdf", array("Attachment"=>0));
//1 = download
//0= preview
$fileupload = $document->output();
// setup email
$message = "Am new to programming and loving it";
$mail = new PHPMailer;
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxx#gmail.com'; // SMTP username
$mail->Password = 'xxxxxx'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('xxxxx#gmail.com', 'james');
$mail->addAddress('xxxx#aol.com', 'name of receiver'); // Add a recipient
$mail->addAddress('xxxxx#yahoo.com'); // Name is optional
//Attachments
$mail->addAttachment($fileupload); // Add attachments
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = $message;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if ($mail->send()){
echo 'Message has been sent';}
else { echo 'Message could not be sent.';}
?>
You would want to create your file on server and save and then pass absolute path of pdf file to addAttachment or alternatively you can also directly attach the DomPDF output without creating a file, like so:
$mail->addAttachment($fileupload,'application/pdf','output.pdf', false);
I am working on a web application using PHP as a server-side and a jQuery framework as a client-side.
One of the scenarios of the application is to send an email with pdf file attached I am doing this using PHPMailer and Dompdf libraries.
I had created a function named sendMail in a file name send.php accept 4 params (receiver email,subject,data,email number) the last param is because I have 5 different emails may be sent depending on the situation and data param is the data will be rendered in the html email body.
The problem is when I call the function from send.php it work as expected the email sent and pdf file created and attached to the email .
but when I require send.php in any other file and call sendMail function I get the email only without any pdf file and the file not even generated or saved on the server.
send.php
<?php
require_once 'dompdf/autoload.inc.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;
require 'PHPMailerAutoload.php';
$body = "test message";
sendMail('peter#w34.co','MLS mail',$body,5);
function sendMail($email,$subject,$body,$index){
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // SMTP authentication
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Port = 587; // SMTP Port
$mail->Username = "peterwilson.intake34#gmail.com"; // SMTP account username
$mail->Password = "Password"; // SMTP account password // TCP port to connect to
$mail->From = 'peter#example.com';
$mail->FromName = 'Wilson';
$mail->addAddress($email); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body=$body;
// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml($body);
// Render the HTML as PDF
$dompdf->render();
$output = $dompdf->output();
$file_to_save= "../work-orderes/file.pdf";
file_put_contents($file_to_save, $output);
$mail->addAttachment('../work-orderes/file.pdf');
if(!$mail->send()) {
// echo $mail->ErrorInfo;
} else {
return 1;
}
}
?>
save.php
<?php
require("sendSmtp/send.php");
session_start();
$body = "Hello World!";
sendMail('peter#w34.co','MLS mail',$body,5);
?>
Any suggestions about why Dompdf not works when calling it from any other file ??
What I have tried
removing dompdf and reinstall the latest stable version from
here
cleaning all code and just leave sendMail function and calling it
try to write the code from the beginnig
I solved it finally!
after debugging I found that everything going fine till $output = $dompdf->output(); after that I get an error on save the file using $file_to_save= "../work-orderes/file.pdf";
this work properly when I call the function sendMail() from send.php but when I call it from another file I get an error regarding accessing the path.
The Answer here that I should use the absolute path not the relative one like below
$file_to_save= $_SERVER['DOCUMENT_ROOT']."\work-orderes/file.pdf";
now the file saved successfully and attached to the email like expected!