用PHP发送带有PDF附件的电子邮件。

17

我正在使用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;
    }
}
请检查我的代码,并让我知道进一步的可能性。先行致谢。
4个回答

11
你可以使用PHPMailer来与FPDF配合使用,而不会发生任何麻烦。你需要修改$pdf->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是个好主意。 - Monirul Islam

9
使用以下简单代码发送带有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_rand}x";
$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.";
}

2
当我尝试这个时,我没有邮件内容 :-( - Maxi
这个功能非常好,但请将对“-{$mime_boundary}”的引用替换为“--{$mime_boundary}”,并在底部将“-{$mime_boundary}-”替换为“--{$mime_boundary}--”,因为这解决了Maximilian提到的问题。 - omikes

6

不需要使用外部库。按照以下格式操作:

$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_rand}x";
$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.";
}

今天是2023年6月27日。而且仍然是完美的回答。请注意,其他一些回复在使用具有附件的爱普生邮件打印时无法正常工作,但omikes的回复表现得非常出色。 - Peter

-1

改变这个:

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

变成这样:

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

如果我这样做,它就不会发送任何PDF附件。 - Monirul Islam
啊,这很有趣...它可能是解决方案,我正在等待Monirul测试并让我们知道...我猜你是在建议,如果他从$msg开始。它会在开头添加一些随机字符,因为它在开始时没有被声明为空?这就是@Kyle的原因吗? - omar-ali
Monirul,仅对于第一行,您无需使用<dot>“。”...对于其余所有行,您应该保留<dot>。 - omar-ali
你需要将字符串连接起来。 - KyleMassacre
哦,别这样 :) 我知道它是拼接..只是懒得写整个“拼接”单词.. :) - omar-ali
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接