Attach pdf in mail through php mail function

To attach a PDF file to an email sent using the PHP mail function, you'll need to use the mime_content_type and base64_encode functions to specify the file type and encode the file contents, respectively. Here's an example code snippet that demonstrates how to do this:

<?php

// Set the email headers
$headers = array(
    'From' => '[email protected]',
    'To' => '[email protected]',
    'Subject' => 'Email with attached PDF',
    'Content-Type' => 'multipart/mixed'
);

// Set the email body
$body = 'This is the email body.';

// Set the PDF file path and name
$pdf_file = 'path/to/your/pdf/file.pdf';
$pdf_name = 'your_pdf_file.pdf';

// Open the PDF file and read its contents
$pdf_contents = file_get_contents($pdf_file);

// Specify the PDF file type
$pdf_type = 'application/pdf';

// Encode the PDF file contents using base64
$pdf_encoded = base64_encode($pdf_contents);

// Create a new MIME message
$message = '';
$message.= 'This is the email body.'. "\r\n";
$message.= 'Content-Type: application/pdf; name="'. $pdf_name. '"'. "\r\n";
$message.= 'Content-Transfer-Encoding: base64'. "\r\n";
$message.= 'Content-Disposition: attachment; filename="'. $pdf_name. '"'. "\r\n";
$message.= $pdf_encoded. "\r\n";

// Send the email using the PHP mail function
mail('[email protected]', 'Email with attached PDF', $message, $headers);

?>

In this example, we:

  1. Set the email headers, including the Content-Type header, which specifies that the email contains a multipart message.
  2. Set the email body.
  3. Set the PDF file path and name.
  4. Open the PDF file and read its contents using file_get_contents.
  5. Specify the PDF file type using the mime_content_type function.
  6. Encode the PDF file contents using base64_encode.
  7. Create a new MIME message by concatenating the email body, PDF file type, and encoded PDF file contents.
  8. Send the email using the PHP mail function.

Note that this code assumes that the PDF file is located on the same server as the PHP script. If the PDF file is located on a different server, you'll need to modify the code to use a different method to retrieve the file contents, such as using curl or file_get_contents with a URL.

Also, keep in mind that this is just a basic example, and you may need to modify the code to suit your specific requirements, such as adding error handling or customizing the email headers and body.