php发送带有PDF附件的电子邮件

Posted

技术标签:

【中文标题】php发送带有PDF附件的电子邮件【英文标题】:php send e-mail with PDF attachment 【发布时间】:2014-02-28 16:11:09 【问题描述】:

我正在使用 FPDF 创建 pdf。 Pdf 生成完美,并且 pdf 也可以通过电子邮件获得。但我也想发送正文消息。我尝试过使用正文消息。示例 细短信This is text message from shohag 但只有pdf附件可用,正文为空。这是我的代码。

function send_pdf_to_user()
    if($_REQUEST['action'] == 'pdf_invoice' )
        require('html2pdf.php');
        $pdf=new PDF_HTML();
        $pdf->SetFont('Arial','',11);
        $pdf->AddPage();

        $text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
        if(ini_get('magic_quotes_gpc')=='1')
        $text=stripslashes($text);
        $pdf->WriteHTML($text);

        //documentation for Output method here: http://www.fpdf.org/en/doc/output.htm
        $attach_pdf_multipart = chunk_split( base64_encode( $pdf->Output( '', 'S' ) ) );


        //define the receiver of the email 
        $to = 'monirulmask@gmail.com';

        //define the subject of the email 
        $subject = 'Test Invoice'; 
        //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: webmaster@test.ch\r\nReply-To: webmaster@test.ch"; 
        //add boundary string and mime type specification 
        $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";       



        $msg .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";
        $msg .= "Content-Transfer-Encoding: base64\r\n";
        $msg .= "Content-Disposition: attachment\r\n";
        $msg .= $attach_pdf_multipart . "\r\n";

        $msg .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n";
        $msg .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
        $msg .= "<p>This is text message from shohag</p>\r\n\r\n";  

        global $message;
        $message = '';
        $mail_sent = @mail( $to, $subject, $msg, $headers );
        //@mail( $to1, $subject, $msg, $headers );
        if(!empty($mail_sent)):
            $message = "Invoice sent succuessfully";
        else:
            $message = "Error occured. Please try again.";
        endif;
    

请检查我的代码,让我知道进一步的可能性。提前致谢。

【问题讨论】:

【参考方案1】:

您可以将 PHPMailer 与 FPDF 一起使用。它可以正常工作,没有任何麻烦。您需要更改 $pdf-&gt;Output 的参数。下载 class.phpmailer.phpPHPMailerAutoload.php 并将其复制到您的工作文件夹。在require('html2pdf.php'); 下方或上方附加class.phpmailer.php。我以前做过这个,所以这会起作用。根据您的代码,这应该可以工作。

function send_pdf_to_user()
    if($_REQUEST['action'] == 'pdf_invoice' )
        require('html2pdf.php');
        require_once('class.phpmailer.php');
        $pdf=new PDF_HTML();
        $pdf->SetFont('Arial','',11);
        $pdf->AddPage();

        $text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
        if(ini_get('magic_quotes_gpc')=='1')
        $text=stripslashes($text);
        $pdf->WriteHTML($text);

        $mail = new PHPMailer(); // defaults to using php "mail()"
        $body = "This is test mail by monirul";
       
        $mail->AddReplyTo("webmaster@test.ch","Test Lernt");
        $mail->SetFrom('webmaster@test.ch', 'Test Lernt');
       
        $address = "monirulmask@gmail.com";
        $mail->AddAddress($address, "Abdul Kuddos");       
        $mail->Subject    = "Test Invoice";       
        $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
       
        $mail->MsgHTML($body);
        //documentation for Output method here: http://www.fpdf.org/en/doc/output.htm       
        $pdf->Output("Test Invoice.pdf","F");
        $path = "Walter Lernt Invoice.pdf";
         
        $mail->AddAttachment($path, '', $encoding = 'base64', $type = 'application/pdf');
        global $message;
        if(!$mail->Send()) 
          $message =  "Invoice could not be send. Mailer Error: " . $mail->ErrorInfo;
         else 
          $message = "Invoice sent!";
        
       
    

【讨论】:

它的工作。谢谢你的努力。使用 PHPmailer 是个好主意。【参考方案2】:

使用这个简单的代码发送带有 pdf 附件的电子邮件。希望这对您有所帮助。谢谢。

// Settings
$name        = "Name goes here";
$email       = "someome@anadress.com";
$to          = "$name <$email>";
$from        = "Gyan-Shah ";
$subject     = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$fileatt     = "./test.pdf"; //file location
$fileatttype = "application/pdf";
$fileattname = "newname.pdf"; //name that you want to use to send or you can use the same name
$headers = "From: $from";

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

// This attaches the file
$semi_rand     = md5(time());
$mime_boundary = "==Multipart_Boundary_x$semi_randx";
$headers      .= "\nMIME-Version: 1.0\n" .
  "Content-Type: multipart/mixed;\n" .
  " boundary=\"$mime_boundary\"";
  $message = "This is a multi-part message in MIME format.\n\n" .
  "--$mime_boundary\n" .
  "Content-Type: text/plain; charset=\"iso-8859-1\n" .
  "Content-Transfer-Encoding: 7bit\n\n" .
  $mainMessage  . "\n\n";

$data = chunk_split(base64_encode($data));
$message .= "--$mime_boundary\n" .
  "Content-Type: $fileatttype;\n" .
  " name=\"$fileattname\"\n" .
  "Content-Disposition: attachment;\n" .
  " filename=\"$fileattname\"\n" .
  "Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
 "--$mime_boundary--\n";

// Send the email
if(mail($to, $subject, $message, $headers)) 

  echo "The email was sent.";


else 

  echo "There was an error sending the mail.";

【讨论】:

当我尝试这个时,我没有邮件内容:-( 这非常有效,但请将-$mime_boundary 的引用替换为--$mime_boundary,并在底部将-$mime_boundary- 替换为--$mime_boundary--,因为这样可以解决Maximilian 提到的问题。【参考方案3】:

真的不需要外部库。请遵循以下格式:

$to          = "email1@domain.com, email2@domain.com"; // addresses to email pdf to
$from        = "sent_from@domain.com"; // address message is sent from
$subject     = "Your PDF email subject"; // email subject
$body        = "<p>The PDF is attached.</p>"; // email body
$pdfLocation = "./your-pdf.pdf"; // file location
$pdfName     = "pdf-file.pdf"; // pdf file name recipient will get
$filetype    = "application/pdf"; // type

// create headers and mime boundry
$eol = PHP_EOL;
$semi_rand     = md5(time());
$mime_boundary = "==Multipart_Boundary_x$semi_randx";
$headers       = "From: $from$eol" .
  "MIME-Version: 1.0$eol" .
  "Content-Type: multipart/mixed;$eol" .
  " boundary=\"$mime_boundary\"";

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

// fetch pdf
$file = fopen($pdfLocation, 'rb');
$data = fread($file, filesize($pdfLocation));
fclose($file);
$pdf = chunk_split(base64_encode($data));

// attach pdf to email
$message .= "--$mime_boundary$eol" .
  "Content-Type: $filetype;$eol" .
  " name=\"$pdfName\"$eol" .
  "Content-Disposition: attachment;$eol" .
  " filename=\"$pdfName\"$eol" .
  "Content-Transfer-Encoding: base64$eol$eol" .
  $pdf . $eol .
  "--$mime_boundary--";

// Send the email
if(mail($to, $subject, $message, $headers)) 
  echo "The email was sent.";

else 
  echo "There was an error sending the mail.";

【讨论】:

【参考方案4】:

改变这个:

$msg .= "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";

到这里:

$msg = "Content-Type: application/octet-stream; name=\"attachment.pdf\"\r\n";

【讨论】:

如果我这样做,那么它不会发送任何 pdf 附件。 啊,这很有趣.. 这可能是解决方案,我正在等待 Monirul 进行测试并让我们知道.. 我猜你是在暗示,如果他以 $msg 开头。它会在开头添加一些随机字符,因为它在开始时没有被声明为null?这就是@Kyle 的原因吗? Monirul,只有第一行,你没有 "."...对于其余的,你应该保留 你必须连接你的字符串。 @omar-ali:它的串联。他正在将字符串“附加”到现有字符串

以上是关于php发送带有PDF附件的电子邮件的主要内容,如果未能解决你的问题,请参考以下文章

带有pdf附件和html消息的php邮件功能

带有附件问题的 PHP Pear Mime 邮件

在批准报价、运行报告、生成 PDF 并发送带有 PDF 作为附件的电子邮件

无法在python中使用MIME发送带有pdf附件的电子邮件

在 Python 中发送带有 HTML+plain_text 电子邮件的 PDF 附件

Prestashop 从 html2pdf 发送邮件附件 pdf