2010-12-04 2 views
12

Я хочу отправить PDF-документ в виде вложения, которое было создано с использованием FPDF. Мой код выглядит так, но приложение никогда не приходит.Email PDF-приложение с PHP с использованием FPDF

<?php 
require('lib/fpdf/fpdf.php'); 

$pdf = new FPDF('P', 'pt', array(500,233)); 
$pdf->AddFont('Georgiai','','georgiai.php'); 
$pdf->AddPage(); 
$pdf->Image('lib/fpdf/giftcertificate.jpg',0,0,500); 
$pdf->SetFont('georgiai','',16); 
$pdf->Cell(40,10,'Hello World!'); 
$doc = $pdf->Output('test.pdf', 'S'); 

//define the receiver of the email 
$to = '[email protected]'; 
//define the subject of the email 
$subject = 'Test email with attachment'; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash 
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \r\n 
$headers = "From: [email protected]\r\nReply-To: [email protected]"; 
//add boundary string and mime type specification 
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 
//read the atachment file contents into a string, 
//encode it with MIME base64, 
//and split it into smaller chunks 
$attachment = chunk_split(base64_encode(file_get_contents($doc))); 
//define the body of the message. 
ob_start(); //Turn on output buffering 
?> 
--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit 

Hello World!!! 
This is simple text email message. 

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit 

<h2>Hello World!</h2> 
<p>This is something with <b>HTML</b> formatting.</p> 

--PHP-alt-<?php echo $random_hash; ?>-- 

--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: application/zip; name="attachment.zip" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?> 
--PHP-mixed-<?php echo $random_hash; ?>-- 

<?php 
//copy current buffer contents into $message variable and delete current output buffer 
$message = ob_get_clean(); 
//send the email 
$mail_sent = @mail($to, $subject, $message, $headers); 
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed"; 

?> 

Кто-нибудь знаком с этим? Я надеюсь использовать функцию PHP mail().

+2

Если это не для целей обучения, использовать библиотеку PHP мэйлера как Swiftmailer , http://swiftmailer.org/ – 2010-12-04 11:42:54

+0

Как говорит Пекка, Swift Mailer - это гораздо лучшая идея, чем отправка почты с помощью вложений вручную. – Orbling 2010-12-04 15:11:02

ответ

19

Это в конечном итоге работает для меня:

<?php 
require('lib/fpdf/fpdf.php'); 

$pdf = new FPDF('P', 'pt', array(500,233)); 
$pdf->AddFont('Georgiai','','georgiai.php'); 
$pdf->AddPage(); 
$pdf->Image('lib/fpdf/image.jpg',0,0,500); 
$pdf->SetFont('georgiai','',16); 
$pdf->Cell(40,10,'Hello World!'); 

// email stuff (change data below) 
$to = "[email protected]"; 
$from = "[email protected]"; 
$subject = "send email with pdf attachment"; 
$message = "<p>Please see the attachment.</p>"; 

// a random hash will be necessary to send mixed content 
$separator = md5(time()); 

// carriage return type (we use a PHP end of line constant) 
$eol = PHP_EOL; 

// attachment name 
$filename = "test.pdf"; 

// encode data (puts attachment in proper format) 
$pdfdoc = $pdf->Output("", "S"); 
$attachment = chunk_split(base64_encode($pdfdoc)); 

// main header 
$headers = "From: ".$from.$eol; 
$headers .= "MIME-Version: 1.0".$eol; 
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\""; 

// no more headers after this, we start the body! // 

$body = "--".$separator.$eol; 
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol; 
$body .= "This is a MIME encoded message.".$eol; 

// message 
$body .= "--".$separator.$eol; 
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol; 
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol; 
$body .= $message.$eol; 

// attachment 
$body .= "--".$separator.$eol; 
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol; 
$body .= "Content-Transfer-Encoding: base64".$eol; 
$body .= "Content-Disposition: attachment".$eol.$eol; 
$body .= $attachment.$eol; 
$body .= "--".$separator."--"; 

// send message 
mail($to, $subject, $body, $headers); 

?> 
3

Я думаю, что у вас есть лишняя команда. Вы используете строку вариант команды Output():

$doc = $pdf->Output('test.pdf', 'S'); 

Затем вы выполняете file_get_contents() на нем:

$attachment = chunk_split(base64_encode(file_get_contents($doc))); 

Это не файл, это файл в строке, поскольку file_get_contents() вернется, если $doc было именем файла.

Просто сократить, что вплоть до:

$attachment = chunk_split(base64_encode($doc)); 

Затем посмотреть, если возникают какие-либо больше ошибок.

+0

У меня больше нет ошибок, но файл никогда не прикреплен. Письмо, отправленное мной, имеет вложение «noname» в 0kb. Любые мысли о том, почему это может быть? Спасибо за вашу помощь. – HWD 2010-12-04 20:32:59

+0

Получение MIME-кодирования для работы вручную очень сложно, особенно когда вы добавляете сложные вложения, я определенно рекомендую использовать почтовую библиотеку в качестве упоминания в вашем вопросе. Кстати, вы, кажется, говорите, что имя файла - файл attachment.zip, и это zip-файл, ни в коем случае вы не закрепили PDF-файл. – Orbling 2010-12-04 23:51:37

19

если вы используете PHPMailer

$attachment= $pdf->Output('attachment.pdf', 'S'); 

$mailer->AddStringAttachment($attachment, 'attachment.pdf'); 

Наслаждайтесь

1
Create one pdf file name as testing.pdf 
<?php 
    //define the receiver of the email 
    $to = '[email protected]'; 

    //define the subject of the email 
    $subject = 'Test email with attachment'; 

    //create a boundary string. It must be unique 
    //so we use the MD5 algorithm to generate a random hash 
    $random_hash = md5(date('r', time())); 

    //define the headers we want passed. Note that they are separated with \r\n 
    $headers = "From: [email protected]\r\nReply-To: [email protected]"; 

    //add boundary string and mime type specification 
    $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 

    //read the atachment file contents into a string, 
    //encode it with MIME base64, 
    //and split it into smaller chunks 
    $attachment = chunk_split(base64_encode(file_get_contents('testing.pdf'))); 

    //define the body of the message. 
    ob_start(); //Turn on output buffering 
    ?> 
    --PHP-mixed-<?php echo $random_hash; ?> 
    Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

    --PHP-alt-<?php echo $random_hash; ?> 
    Content-Type: text/plain; charset="iso-8859-1" 
    Content-Transfer-Encoding: 7bit 

    Hello World!!! 
    This is simple text email message. 

    --PHP-alt-<?php echo $random_hash; ?> 
    Content-Type: text/html; charset="iso-8859-1" 
    Content-Transfer-Encoding: 7bit 

    <h2>Email Pdf File Attachements</h2> 
    <p>This is something with <b>HTML</b> formatting.</p> 

    --PHP-alt-<?php echo $random_hash; ?>-- 

    --PHP-mixed-<?php echo $random_hash; ?> 
    Content-Type: application/pdf; name="attachment.pdf" 
    Content-Transfer-Encoding: base64 
    Content-Disposition: attachment 

    <?php echo $attachment; ?> 
    --PHP-mixed-<?php echo $random_hash; ?>-- 

    <?php 
    //copy current buffer contents into $message variable and delete current output buffer 
    $message = ob_get_clean(); 
    //send the email 
    $mail_sent = @mail($to, $subject, $message, $headers); 
    //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
    echo $mail_sent ? "Mail sent" : "Mail failed"; 
?> 
Смежные вопросы