【问题标题】:php send e-mail with PDF attachmentphp send e-mail with PDF attachment
【发布时间】:2021-12-09 15:34:14
【问题描述】:

I am creating pdf using FPDF . Pdf is generating perfectly and also pdf is available with email. But i want to send body message also. I have tried with body message. Example Fine text message This is text message from shohag But only pdf attachment is available and body is empty. Here is my code.

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;
    }
}

Please check my code and let me know further possibility. Thanks in advance.

【问题讨论】:

    标签: php email-attachments fpdf


    【解决方案1】:

    You can use PHPMailer with FPDF . It works properly without any hassle. You need to change parameter for $pdf-&gt;Output . Download and copy class.phpmailer.php and PHPMailerAutoload.php to your work folder. Attach class.phpmailer.php below or above require('html2pdf.php'); . I have done this before so this will work. According to your code this should work.

    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!";
            }
           
        }
    }
    

    【讨论】:

    • Its working. Thank your effort. Using PHPmailer is good idea.
    【解决方案2】:

    Use this simple code to send email with pdf attachment. Hope this help you. Thanks.

    // 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      .= "
    MIME-Version: 1.0
    " .
      "Content-Type: multipart/mixed;
    " .
      " boundary="{$mime_boundary}"";
      $message = "This is a multi-part message in MIME format.
    
    " .
      "--{$mime_boundary}
    " .
      "Content-Type: text/plain; charset="iso-8859-1
    " .
      "Content-Transfer-Encoding: 7bit
    
    " .
      $mainMessage  . "
    
    ";
    
    $data = chunk_split(base64_encode($data));
    $message .= "--{$mime_boundary}
    " .
      "Content-Type: {$fileatttype};
    " .
      " name="{$fileattname}"
    " .
      "Content-Disposition: attachment;
    " .
      " filename="{$fileattname}"
    " .
      "Content-Transfer-Encoding: base64
    
    " .
    $data . "
    
    " .
     "--{$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.";
    }
    

    【讨论】:

    • When I try this I don't have a mail content :-(
    • This works fantastically, but please replace the reference to -{$mime_boundary} with --{$mime_boundary} and at the bottom replace -{$mime_boundary}- with --{$mime_boundary}-- as this resolves the issue Maximilian mentioned.
    【解决方案3】:

    No external libraries are necessary really. Follow this format:

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

    【讨论】:

      【解决方案4】:

      change this:

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

      To this:

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

      【讨论】:

      • If i do this then it won't send any pdf attachment.
      • Ah this is interesting.. it could be the solution, I'm waiting for Monirul to test and let us know.. I guess you're suggesting that, if he starts with the $msg. it'd add some random chars at the beginning because it hasn't been declared as null at the start? is that why @Kyle?
      • Monirul, only for the first line, you do without the <dot> "."...for the rest of them, you should keep the <dot>
      • well you have to concatenate your strings.
      • @omar-ali: Its concatenation. He is "appending" strings to an existing string
      猜你喜欢
      • 2022-01-14
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      • 2017-07-12
      • 2015-04-11
      • 2019-05-22
      相关资源
      最近更新 更多