I am using PHP Mailer to basically send a interactive PDF to an email address. This works locally calling the script from the PDF to the server, but does not work when the PDF is completed on the server.
Code is below:
<?php
if(!isset($HTTP_RAW_POST_DATA)) {
echo "The Application could not be sent. Please save the PDF and email it manually.";
exit;
}
echo "<html><head></head><body><img src='loading.gif'>";
//Create PDF file with data
$semi_rand = md5(time());
$pdf = $HTTP_RAW_POST_DATA;
$file = $semi_rand . ".pdf";
$handle = fopen($file, 'w+');
fwrite($handle, $pdf);
fclose($handle);
//
require_once('class/class.phpmailer.php');
include("class/class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(false); // the true param means it will throw exceptions on errors, which we need to catch
$mail -> CharSet = "UTF-8";
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "HOST"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "HOST";
$mail->Port = 465;
$mail->Username = "USERNAME";
$mail->Password = "PASSWORD";
$mail->AddAddress('TO ADDRESS');
$mail->SetFrom('FROM ADDRESS');
$mail->Subject = 'SUBJECT';
$mail->Body = 'Please see attachment';
$mail->IsHTML(true);
$mail->AddAttachment($file); // attachment
$mail->Send();
//Delete the temp pdf file then redirect to the success page
// unlink($file);
echo '<META HTTP-EQUIV="Refresh" Content="0; URL="1.1.1.1">';
exit;
} catch (phpmailerException $e) {
//you can either report the errors here or redirect them to an error page
//using the above META tag
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
//Verify the temporary pdf file got deleted
unlink($file);
?>
Is there something I am missing? All values for the $mail (host, username, password etc) are correct - but when it creates the PDF to send, it only comes through as < 1kb. My PDF calls this PHP file on submit.
You can't create PDFs like simple txt or csv files with fwrite. It is a more sophisticated file type.
Look into DomPDF which for your setting may look somewhat like the below (assuming $HTTP_RAW_POST_DATA is an html document):
require("dompdf_config.inc.php");
$semi_rand = md5(time());
$pdf = file_get_contents('http://www.pdfpage.com/');
$file = $semi_rand . ".pdf";
$dompdf = new DOMPDF();
$dompdf->load_html($pdf);
$dompdf->set_paper('a4', 'portrait');
$dompdf->render();
$dompdf->stream($file, array('Attachment' => '0'));
...
// USE $file as needed in email attachment
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 understand PHPmailer is one of the best if not the best php libraries for sending emails. Of late I have been working on an API using slimphp and was trying to send an email with a file attachment. Since slimphp doesn't expose the php $_FILES (at-least no that straight forward) but uses $request->getUploadedFiles() , I wanted to know how you can send an email with a file attachment using slimphp and PHPMailer
use Psr\Http\Message\UploadedFileInterface; //slimphp File upload interface
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$app = new \Slim\App;
$app->post('/send_mail_Attachment', function ($request, $response){
//get the file from user input
$files = $request->getUploadedFiles();
$uploadedFile = $files['fileName']; //fileName is the file input name
$filename = $uploadedFile->getClientFilename();
$filesize = $image->getSize();
//check file upload error
if ($uploadedFile->getError() != UPLOAD_ERR_OK) {
//return your file upload error here
}
//Check file size
if ($filesize > 557671) {
//return error here if file is larger than 557671
}
//check uploaded file using hash
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $filename));
//upload file to temp location and send
if (move_uploaded_file($uploadedFile->file, $uploadfile)){
//send email with php mailer
$mail = new PHPMailer(true);
try{
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.zoho.com'; //change to gmail
$mail->SMTPAuth = true;
$mail->Username = 'admin#yourdomain.com';
$mail->Password = 'your password here';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('admin#yourdomain.com', 'Web Admin');
$mail->addAddress('email address your sending to');
$mail->isHTML(true); //send email in html formart
$mail->Subject = 'email subject here';
$mail->Body = '<h1>Email body here</h1>';
$mail->addAttachment($uploadfile, $fileName); //attach file here
$mail->send();
//return Email sent
}
catch (Exception $e) {
$error = $mail->ErrorInfo;
//return error here
}
}
//return error uploading file
});
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 have a script that runs FPDF that creates and stores a PDF file in a folder.
That works fine.
My question is, am I able to send an email in that same script?
I have attempted it but i always get "Page cannot be displayed"
EDIT I dont want the files attached to the email. I just wish to send a email with some wording thats all.
Wont paste my whole code as its just the end that has the problem:
//display pdf
mkdir("FileBrowser/files/$name", 0777);
$total = count($_FILES['files']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "FileBrowser/files/$name/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
$filename = "FileBrowser/files/$name/$name.pdf";
$pdf->Output($filename, 'F');
require ('PHPMailer/class.phpmailer.php');
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = '****'; // Specify main and backup server
$mail->Port = 587; // Set the SMTP port
$mail->SMTPAuth = true;
$mail->Username = '****'; // SMTP username
$mail->Password = '****'; // SMTP password
$mail->From = 'Testing#test.co.za';
$mail->FromName = 'Testing';
$mail->AddAddress('****', 'John Smith'); // Add a recipient
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <strong>in bold!</strong>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
?>
i am saving excel in folder in my server(note excel is saving in server),i am trying to sent email with an excel attachment that saved in my server,but i didn't receive an email with the attachment(i.e: i received email without an attachment),below is my code please guide me how to do it.
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('/data/data/www/ms/pricelists/newxcelexample.xls');
$my_path ="/data/data/www/ms/pricelists/newxcelexample.xls";
include "class.phpmailer.php"; // include the class file name
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
//$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "mail.xichlomobile.com";
$mail->Port = "25"; // or 587
$mail->IsHTML(true);
$mail->Username = "************";
$mail->Password = "**********";
$mail->SetFrom("**************");
$mail->Subject = Test;
$mail->Body = "Test";
$mail->AddAddress("*********");
$mail->AddAttachment($my_path);
if(!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}
else{
echo "<span style='font-size:45px;color:#000000;'>Message has been sent</span><br><br>";
}
Have you controlled that the file is really present and gets saved correctly? Has the web server the right do read the file (normally readable by the user www-data)?
Perhaps try to supply also the filename to AddAttachment:
$mailer->AddAttachment($my_path, basename($my_path));
// or
$mailer->AddAttachment($my_path, basename($my_path), "quoted-printable", "application/vnd.ms-excel") ;
If you're using a newer version of PHPMailer, you can also use exceptions to see what's happening. Perhaps it isn't preventing the mail from going out but from attaching the file.
try {
// preparing the email just before the mail->Send()
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
Try sending another file for once, e.g. a *.txt or *.zip (to check if you have limitations on the file types you can send, which would be unlikely for a excel file).