Jump to content

Save PDF file to mysql and then send it as email attachment


xox

Recommended Posts

I would like to store PDF file into mysql (this part works) and then send it as email attachment and it should be retrieved from mysql table.

 

Here's the code I have for now, but what it gives me is 0bytes large PDF file

Saving PDF to mysql (it works), because size of blob in mysql table is OK.

$fp      = fopen('generated.pdf', 'r');
$content = fread($fp,filesize('generated.pdf'));
$content = addslashes($content);
fclose($fp);
$DB->Query('insert into pdf_files (pdf_file, name) values ("'.$content.'", "'.$name.'")');

 

And here's the mailing part

<?php
$query = "SELECT name, pdf_file FROM pdf_files 
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array ( $result))
{

	$fileContent =$row['pdf_file'];
	$fileName=$row['name'];

} 

$fileatt = $fileContent; // getting file
$fileatt_type ="application/pdf"; //type of file
$fileatt_name = "attachment.pdf"; // name
$fileatt_size = $fileSize;

$email_from = "[email protected]"; // mail from
$email_subject = "Testtt"; // subject
$email_message = "Testtt.<br>";
$email_message .= "Testtt.<br>"; // Message
$email_to = $mail_user; // users mail

$headers = "From: ".$email_from; 

$file = fopen($fileatt,'rb'); 
$data = fread($file,filesize($fileatt)); 
fclose($file); 

$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

$headers .= "\nMIME-Version: 1.0\n" . 
"Content-Type: multipart/mixed;\n" . 
" boundary=\"{$mime_boundary}\""; 

$email_message .= "Testtt.\n\n" . 
"--{$mime_boundary}\n" . 
"Content-Type:text/html; charset=\"iso-8859-1\"\n" . 
"Content-Transfer-Encoding: 7bit\n\n" . 
$email_message .= "\n\n"; 

$data = chunk_split(base64_encode($data)); 

$email_message .= "--{$mime_boundary}\n" . 
"Content-Type: {$fileatt_type};\n" . 
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" . 
//" filename=\"{$fileatt_name}\"\n" . 
"Content-Transfer-Encoding: base64\n\n" . 
$data .= "\n\n" . 
"--{$mime_boundary}--\n"; 

$ok = @mail($email_to, $email_subject, $email_message, $headers); 

if($ok) { 
echo "<font face=verdana size=2><center>Mail was sent</center>";

} else { 
die("Error!"); 
} 
?>

 

Well I know that but it's the only way for now because PDF files will have limited "life time".

 

Unlinking a file when it's 'life time' is over is easier, safer and less resource-intensive than dealing with encoding/decoding binary in MySQL. But whatever works for you. :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.