Sending File Attachment with PHPMailer in Slim php framework - php

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
});

Related

Could not access file: Could not access file: Could not access file: PHP Mailer issue

Code is working fine without attachments. and attachment code is working fine on another page anybody can help to solve this?
<?php
require('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->Username = "info#guildsconnect.org";
$mail->Password = "Guildsconnect";
$mail->Host = "webs10rdns1.websouls.net";
$mail->Mailer = "smtp";
$mail->SetFrom($contact_email, $contact_name);
$mail->AddReplyTo($contact_email, $contact_name);
$mail->AddAddress("hashimbhatti906#gmail.com");
$mail->Subject = $sub1;
$mail->WordWrap = 80;
$mail->MsgHTML($emailbodyis);
foreach ($_FILES["attachment"]["name"] as $k => $v) {
$mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}
$mail->IsHTML(true);
if(!$mail->Send()) {
$_SESSION["error"] = "Problem in Sending Mail.";
} else {
$_SESSION["success"] = "Mail Sent Successfully.";
}
?>
Firstly, you're using a very old and unsupported version of PHPMailer, so upgrade. It also looks like you have based your code on a very old example.
You are not handling the file upload safely, not validating the uploaded file before trying to use it, as per the PHP docs.
PHPMailer provides an example that shows how to handle and upload and attach it correctly. The key parts are to use move_uploaded_file() to validate the upload before using it, and not to trust the supplied filename. To paraphrase the example:
//Extract an extension from the provided filename
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
//Define a safe location to move the uploaded file to, preserving the extension
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name'])) . '.' . $ext;
if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadfile)) {
//Now create a message
$mail = new PHPMailer();
...
//Attach the uploaded file
if (!$mail->addAttachment($uploadfile, 'My uploaded file')) {
$msg .= 'Failed to attach file ' . $_FILES['attachment']['name'];
}
if (!$mail->send()) {
$msg .= 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$msg .= 'Message sent!';
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
You don't need to set Mailer yourself; it's already done for you by isSMTP().

Sending email with PHPMailer and creating PDF

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;
}
?>

PHP Mailer -> PDF to Email provides blank PDF as attachment

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

How to send an email with a excel attachment

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).

PHPMailer problem

I am new to php. Trying to send confirmation about user upload. I am trying to use PHP Mailer for this. And have the following code but it doesn't work. Any help would be appreciated.
<?php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
// $fileTypes = str_replace('*.','',$_REQUEST['fileext']);
// $fileTypes = str_replace(';','|',$fileTypes);
// $typesArray = split('\|',$fileTypes);
// $fileParts = pathinfo($_FILES['Filedata']['name']);
// if (in_array($fileParts['extension'],$typesArray)) {
// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);
move_uploaded_file($tempFile,$targetFile);
echo "1";
//Send confirmation email
require_once('_mailClasses/class.phpmailer.php');
include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = 'There is a new online order. Please check your order folder.';
//$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.splashoflondon.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.splashoflondon.com"; // sets the SMTP server
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "adolphus#splashoflondon.com"; // SMTP account username
$mail->Password = "correctpassword"; // SMTP account password
$mail->SetFrom('adolphus#splashoflondon.com', 'Splash of London');
$mail->AddReplyTo("ali#xgreen.co.uk","First Last");
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address = "ali#xgreen.co.uk";
$mail->AddAddress($address, "John Doe");
$mail->Send();
}
?>
As you are new to PHP, I highly recommend you check out basic debugging techniques here:
http://www.ibm.com/developerworks/library/os-debug/
It's a good read and you'll see your skills as a troubleshooter jump 10-fold.

Categories