I am using the below script to validate if the uploaded files are pdf and if it is send it with phpmailer. It send the email but there is no attachment. Also, it allows me to attach non pdf files as well. Please help.
ob_start();
require("class.phpmailer.php");
if(isset($_FILES['upload']['tmp_name'])){
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime=finfo_file($finfo, $_FILES['upload']['tmp_name']);
if($mime=='application/pdf'){
$message = "some message";
$mail = new PHPMailer();
$mail->From = ('sample#youdomain.net');
$mail->AddAddress=('sample#youdomain.net');
$mail->Subject = "Submitted files";
$mail->Body = $message;
$mail->WordWrap = 50;
foreach($_FILES['upload']['tmp_name'] as $upload)
if(!empty($upload)) {
$mail->AddAttachment($upload);
}
$mail->Send();
header("Location: thankyou.php");
exit();
}}
Currently you have:
if( ... ) {
...
if($mime=='application/pdf') {
}
}
// some code you want to be executed
// only if the mime type is application/pdf
But you want:
if (...) {
..
if ($mime=='application/pdf') {
// place the code you want to be executed
// only if the mime type is application/pdf
// here - before the closing }
}
}
Related
I've got problem with attachment name, if there are polish language diacritical signs, it won't display those signs.
I added just below php mailer class $mail->CharSet = 'UTF-8'; and it works for email body text( without it I had the same problem), but not for attachments. Also I had a similar problem with user name, but solved it with utf8_decode() function. Unfortunately that function is not working with attachment's name in my case.
<?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\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'autoload.php';
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
//$mail->addCustomHeader('Content-Type', 'text/plain;charset=utf-8');
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$honeypot = $_POST['honey'];
$user_name = utf8_decode($_POST['name']);
$user_email = $_POST['email'];
$user_message = $_POST['message'];
$user_phone = $_POST['phone'];
$honeypot = trim($_POST["honey"]);
$max_size = 2 * 1024 * 1204; //2mb
$attachment = $_FILES['uploaded-file'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(!empty($honeypot)) {
echo "NO SPAM!";
exit;
} else {
$mail = new PHPMailer; //From email address and name
$mail->isMail();
//sender
$mail->From = $user_email;
$mail->FromName = $user_name;
//recipient
$mail->addAddress("jaroslaw.mor#gmail.com");
//mail subject
$mail->Subject = "Zapytanie ze strony www";
$mail->isHTML(true);
//body mail
$mail->Body = "Telefon:$user_phone<br><br>Treść wiadomośći:<br>$user_message";
$mail->AltBody = "Telefon:$user_phone\n$content";
//attachment
if(isset($attachment)) {
for ($i = 0; $i < count($_FILES['uploaded-file']['name']); $i++) {
if ($_FILES['uploaded-file']['error'][$i] !== UPLOAD_ERR_OK) continue;
$file_TmpName = $_FILES['uploaded-file']["tmp_name"][$i];
$file_name = utf8_decode( $_FILES['uploaded-file']["name"][$i]);
if ($_FILES['uploaded-file']['size'][$i] > $max_size) {
echo "file is too big";
die();
}
else{
move_uploaded_file($file_TmpName, "uploads/" . $file_name);
$mail-> AddAttachment("uploads/". $file_name);
}
}//for
}//isset
if(!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
exit();
}
else {
header("Location: sent.html");
exit();
}//if send else
}//honey else end
}//post end
You can try to add this code before attachment upload:
setlocale( LC_ALL, "pl_PL.UTF-8" );
Try force encoding for attachment:
$mail->AddAttachment("uploads/", $file_name, $mail::ENCODING_BASE64, PHPMailer::filenameToType($file_name).'; charset=utf-8');
I tried all methods from here - without a positive result. By the accident I opened PHPMailer.php and noticed that there are some options connected with charset encoding, changed settings there and now it works.
Thx all for clues.
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
I use this php mailer
every things are O.k. but when I attach a file, corrupted file receive in destination email. for example when I send a pdf file receiver can't open it.
and this is my code in using phpmailer:
$target_path = "upload_files/";
$target_path = $target_path . basename( $_FILES['attach']['name']);
if(move_uploaded_file($_FILES['attach']['tmp_name'], $target_path)) {
} else{
}
//eupload file end
require_once 'phpmailer/phpmailer.inc.php';
$mail = new PHPMailer();
$body = $message;
$body = eregi_replace("[\]",'',$body);
$mail->AddReplyTo($email, $fname." ".$lname);
$mail->FromName = $fname." ".$lname;
$mail->From = $email;
$mail->AddAddress("email address", "some one");
$mail->Subject = "something";
$mail->body = $body;
$mail->AddAttachment($target_path); // attachment
if(!$mail->Send()) {
} else {
}
Your PHPMailer have critical errors try it
Must be your Header include file's are wrong
becouse this is the basic mistake in attachments
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
:P
this is my first post and I hope that I can get some help regarding adding an attachment field in my phpMailer contact form. I have already added an uploader [browse] bar in the html website but I don't know how to link it with the phpmailer. do I have to declare it at the package which is phpmailer.php or do something with it?
I would really appreciate some help. Below is my desperate attempt.
Snippet from the code:
<?
$body = ob_get_contents();
$to = 'xxx#xxxx.com>';
$email = $email;
$subject = $subject;
$fromaddress = "xxx#xxxx.com";
$fromname = "Online Contact";
require("phpmailer.php"); //<<this is the original pack
$mail = new PHPMailer();
$mail->From = "xxx#xxxx.com";
$mail->FromName = "My Name";
$mail->AddBCC("xxx#xxxx.com","Name 1");
$mail->AddAddress( $email,"Name 2");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = "This is the text-only body";
// attachment
$mail->AddAttachment('uploadbar', 'new_file.pdf'); // the name of my html uploader is uploadbar, clicking browse to locate a file
if(!$mail->Send()) {
$recipient = 'xxx#xxxx.com';
$subject = 'Contact form failed';
$content = $body;
mail($recipient, $subject, $content, "From: xxx#xxxx.com\r\nReply-To: $email\r\nX-Mailer: DT_formmail");
exit;
}
?>
Had the same problem, try this
$mail->AddAttachment($_SERVER['DOCUMENT_ROOT'].'/file-name.pdf');
First, make sure your upload form has enctype='multipart/form-data' as in <form method=post action=file.php enctype='multipart/form-data'>.
then, use this code in your phpmailer handler file
foreach(array_keys($_FILES['files']['name']) as $key) {
$source = $_FILES['files']['tmp_name'][$key];
$filename = $_FILES['files']['name'][$key];
$mail->AddAttachment($source, $filename);
}
Make sure attachment file name should not contain any special character and check the file path also correct.
eg: [file name.pdf] Should be like [filename.pdf]
I have a form that im trying to get emailed on submit using PHPmailer. For some reason, phpmailer is sending the attachments of the email, but not the body/message. Heres my phpmailer file..
$name = "Purchase Form";
$email_subject = "New Purchase Ticket";
$body = "geg";
foreach ($_REQUEST as $field_name => $value){
if (!empty($value)) $body .= "$field_name = $value\n\r";
}
$Email_to = "jonahkatz#yahoo.com"; // the one that recieves the email
$email_from = "No reply!";
//
//==== PHP Mailer With Attachment Func ====\\
//
function SendIt() {
//
global $attachments,$body,$name,$Email_to,$email_subject,$email_from;
//
$mail = new PHPMailer();
$mail->IsQmail();// send via SMTP
$mail->From = $email_from;
$mail->FromName = $name;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
$mail->IsHTML = true;
$mail ->MsgHTML($body);
$mail->AltBody = 'to view blah';
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
if(move_uploaded_file($file['tmp_name'], $target_path)) {
echo "the file ".basename($file['name'])." has been uploaded";
}else {
echo "there was an error";
}
$mail->AddAttachment($target_path);
}
$mail->Subject = $email_subject;
if(!$mail->Send())
{
}
//
{echo "Message has been sent";}
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
unlink($target_path);}
}
SendIt();
}
?>
Any input? Thanks.
->MsgHTML() doesn't set the body. It returns a modified version with inlined-img urls and whatnot and DOES set the AltBody to a text-version of the HTML. You still need to do
$mail->Body = $body;