Problem in sending excel file as attachment using mail function in php? - php

I have used this code from link below to send excel file as attachment.
http://www.hotscripts.com/forums/php/22626-php-form-excel-then-send-email-attachment.html
Here is the code I have used:
<?php
ob_start();
?>
<html>
<head><title></title>
</head>
<body>
<body>
<center>
<table>
<tr>
<td>Name:</td><td>My Name</td>
</tr>
<tr>
<td>Address:</td><td>My address</td>
</tr>
<tr>
<td>Gender:</td><td>Female</td>
</tr>
</table>
</body></html>
<?php
$FILE_CONTENTS = ob_get_contents();
ob_clean();
// include the class
include("../includes/classes/class.mailer.php");
$recipient = "myid#domain.com";
$from = "myid#domain.com";
// subject
$subject = "Subject of email";
// email message
$message = "
Here goes the message.
";
$myEmail = new EPDEV_Emailer($recipient, $from, $subject);
$myEmail->addText($message);
$myEmail->addFile("my.xls", "application/vnd.ms-excel", $FILE_CONTENTS);
$myEmail->send();
?>
I get excel file in mail but the file does not contain the lines as the normal excel file contains. But i need the file with lines as excel file contains. Can anyone suggest me what the problem might be.
Thanks in advance

I think that you should split your problem in two:
Do you have problems with reading other file types? Try to send a text file and a JPG and see if you have problems reading them as well.
Are you sure the Excel files are OK? Try to save them locally on server, then download by FTP and try to open.
I would guess that the problem is in generating the Excel files (2.), not with sending them by email (1.). But that's just a guess.

Related

PHP DOMPDF error when passing variables from Form or other script file

I am trying to generate PDF file in PHP wit DOMPDF, the variables will be passed from a <form>.
But something is wrong when viewing the PDF file.
If I hardcode the variables within same file, it works fine, but when I pass them from a <form> in a separate script file it shows that error.
Code:
<?php
require __DIR__ . "/vendor/autoload.php";
use Dompdf\Dompdf;
use Dompdf\options;
$staff = $_POST['staff'];
$asset = $_POST['asset'];
$serial = $_POST['serial'];
$description = $_POST['description'];
$designation = "ICT Assistant";
$mission = "Sudan Mission-Khartoum Office";
$crdate = date("d:m:Y");
$dompdf = new Dompdf (["chroot" =>__DIR__]);
$dompdf->setpaper("A4", "landscape");
$html = file_get_contents("aaf.html");
$html = str_replace(["{{name}}","{{designation}}","{{mission}}","{{date}}","{{asset}}"," {{description}}","{{serial}}"],[$staff,$designation,$mission,$crdate,$asset,$description,$serial],$html);
$dompdf->loadhtml($html);
$dompdf-> render();
$dompdf-> stream("Asset Form.pdf",["Attachment"=>0]);
?>
Trying to create a dynamin PDF using DOMPDF, I pass the variables from a <form>.
I have a form that receive info from the user, then I want to insert these info into a PDF file. My problem is when I run the code I receive following error message :error message and no PDF file generated.
below is the form code:
<Form action="tsets.php" method="post">
<input type="text" name="staff"><br>
<input type="text" name="asset"><br>
<input type="text" name="serial"><br>
<input type="text" name="description">
</Form>
Dear Cbros : thanks a lot for your replay , but I tried to download the file and open it with Adobe PDF but also the file is corrupted .
enter image description here

php not working properly in mail()

I am trying to send the information as a mail to the admin
Below is the mail code and I am reading this using file_get_contents() in another file.
<!doctype html>
<?php
require_once("mysqlconnect.php");
session_start();
?>
<html>
<head>
<link rel="stylesheet" href="css/mail.css">
</head>
<body>
<table border="2">
<?php
$q="select * from profile where mobile=2147483647";
$result=mysqli_query($conn,$q);
while($row = mysqli_fetch_assoc($result))
{
foreach($row as $key=>$value)
{
if($key=="Email")
echo"<tr><th>$key</th><td><a href='mailto:$value; target='_blank'>$value</td></tr>";
else
echo"<tr><th>".str_replace('_',' ',$key)."</th> <td>$value</td></tr>";
}
}
?>
</table>
</body>
</html>
<?php
session_destroy();
?>
The result of this code in the mail is the PHP code itself..
$value) { if($key=="Email") echo"
$key $value
"; else echo"
".str_replace('_',' ',$key)." $value
"; } } ?>
file_get_contents returns the content of a file as string. It does not executes the code inside it.
To use the HTML from a php file you can use php's buffer.
Like this:
ob_start();
include('file_path_here');
$HTML = ob_get_clean();
This will store the output of the file in the $HTML variable.
file_get_contents literally reads in a file as a string. If you're reading in a PHP file using that method, it'll literally return the code, which is what you're getting.
If you want to send HTML as an e-mail, use something like a template system (sitecrafting.com/blog/top-5-php-template-engines) or build a string and pass it onto the mail() function.
PHP documentation: file_get_contents

Simultaneous file upload to the same directory

For part of my web app, I'm attempting to upload 1 file under 2 different names. The first name is the original file name that the user specified. This is to be used for reference later on in my app. The second name is an altered name (simply adding in a counter variable). For uploading a single file using move_uploaded_file($name, $path), it works like a charm. When I attempted to call one move_uploaded_file(...) after the other, only the first function would upload a file. The second function would not return an error message.
After looking online, it seemed that this could be accomplished with a loop. I placed the names and the paths in an array, loop through it with a foreach loop but only the first file is uploaded.
Below are the files and their relevant portions as some are lengthy.
mainPage.php applies a header across all of my pages.
verifyFile.php is the file that does the uploading as well as verifying the bulk processing to check that the file is valid.
workPage.php
<?php
session_start();
require("mainPage.php");
?>
<link rel = "stylesheet" type = "text/css" href = "CSS/workpageCSS.css" />
<div id = "pageContainer">
<form enctype = "multipart/form-data" action = "verifyFile.php" method = "post">
<table border = "0" cellpadding = "2" cellspacing = "5">
<tr>
<td>
<label for = "fileName">Select file to upload</label>
</td>
<td>
<input type = "file" name = "file" id = "fileName" placeholder = "Choose file path" autofocus = "autofocus" required = "required" />
</td>
</tr>
<tr>
<td></td>
<td><input type = "submit" value = "Load file" /></td>
</tr>
</table>
</form>
</div>
Portion of verifyFile.php that uploads the file.
Attempt 1:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
$dupFile = appendFileName(basename($_FILES['file']['name']));
$origToUpload = basename($_FILES['file']['name']);
$targetPath = ("uploads/".$dupFile);
$origTargetPath = "uploads/".$origToUpload;
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
#echo("Successfully uploaded ".basename($_FILES['file']['name']));
} else {
echo("Failed 1<br />");
}
/*move_uploaded_file($_FILES['file']['tmp_name'], $origTargetPath); Does not upload but no errors are generated */
?>
Attempt 2
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1')
$filesToUpload = array($targetPath, $origTargetPath);
foreach($filesToUpload as $toUpload) {
if(move_uploaded_file($_FILES['file']['tmp_name'], $toUpload)) {
echo("worked!"); /* first time is successful and $targetPath is loaded onto my server */
} else {
echo("neg"); /* nothing is uploaded and returns neg */
}
}
?>
$origTargetPath and $targetPath are both valid since if I reverse them in my array, only the first file is correctly uploaded.
For additional information, I'm using Apache via XAMPP.
When you call move_upload_file, php will move the file from the file temporary location, to the one you specified. So you can't move the file twice.
What you are looking for is the copy function. In your case (first attempt):
copy($targetPath, $origTargetPath);
You could also consider symlink

Reading a php file from another php file

I currently have a php file that I'm using as a template but I need it to read in data from another php file that I'm using for the page content. I'm doing it this way to save on code and time, however it doesn't appear to be working. I have done a test with shorter amounts of code but it still isn't working. they are both .php files.
Code -
<html>
<head>
<title></title>
</head>
<body>
<?php
$temp = 'test-2.php';
$file = fopen($temp, 'r');
$cont = fread($file, filesize($temp));
print $cont;
fclose($file);
?>
</body>
test-2.php
<?php
echo 'hello world';
?>
just use <?php include('test-2.php'); ?> surely that'll do what you want?

Embedded image in HTML mail shows attached in stead of in template

I'm sending HTML mails with swiftmailer. It all works pretty great, my HTML mails are showing up just fine in all clients. I have quite the knowledge of building email templates. Sending them myself not so much...
The problem exists in gmail and hotmail. The image is not showing up. It shows just fine in Thunderbird for instance... gmail is leaving my image blank and adds it as an attachment (at the bottom of the mail, like i'm sending birthday pictures..).
Any ideas?
I've got the following code:
function deliverMail($subject, $data, $from, $to, $template){
if($_SERVER['SERVER_ADDR'] !== '::1'){
if (!is_array($to)){
$to = array($to);
}
$from = explode(",", $from);
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('mail.xxx.nl', 25)
->setUsername('xxx')
->setPassword('xxx');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance($subject);
$image = $message->embed(Swift_Image::fromPath($_SERVER['DOCUMENT_ROOT'].'/templates/emails/xxx.jpg'));
// open the file
$sourcefile = $_SERVER['DOCUMENT_ROOT'].'/templates/emails/'.$template.'.html.tpl';
$fh = fopen($sourcefile, 'r');
$htmltemplate = fread($fh, filesize($sourcefile));
fclose($fh);
// set the content
if($template == 'confirm'){$replaceOld = array("[*code*]", "[*imgsrc*]");}
if($template == 'notify'){$replaceOld = array("[*url*]", "[*imgsrc*]");}
$replaceNew = array($data, $image);
$body = str_replace($replaceOld, $replaceNew, $htmltemplate);
$message->setFrom(array($from[0] => $from[1]))
->setTo($to)
->setBody($body, 'text/html');
if (!$mailer->send($message, $failures)){
return "Failures:";
return print_r($failures);
}else{
return 'success';
}
}
}
Which will render the image in my template here:
<td id="head" height="80" width="640" colspan="3" valign="top" align="left">
<image src="[*imgsrc*]" width="140" height="80" alt="xxx"/>
</td>
I have seen this behaviour in GMail as well and think this is just how GMail displays mail with embedded images.
See this link for more information:http://www.getelastic.com/email-design-for-gmail/
Did you know that Gmail disables
images in HTML emails by default, even
if your customer has added you to his
or her safe list?
Wow, finally settled this. "image" is not a valid HTML tag of course... after trying 3 different php libraries i found this..
<td id="head" height="80" width="640" colspan="3" valign="top" align="left">
<image src="[*imgsrc*]" width="140" height="80" alt="xxx"/>
</td>

Categories