How to attach pdf file in php mail function
To attach a PDF file to a PHP mail function, you can use the mail()
function's additional_headers
parameter to specify the attachment. Here's an example:
<?php
$to = '[email protected]';
$subject = 'Test PDF Attachment';
$message = 'This is a test message';
// Set the PDF file path and name
$pdf_file = 'path/to/example.pdf';
$pdf_name = 'example.pdf';
// Set the email headers
$headers = 'From: [email protected]'. "\r\n".
'Reply-To: [email protected]'. "\r\n".
'Content-Type: text/plain; charset=UTF-8'. "\r\n".
'Content-Disposition: attachment; filename="'. $pdf_name. '"';
// Set the email body
$body = $message;
// Send the email
mail($to, $subject, $body, $headers, $pdf_file);
In this example, we're using the mail()
function to send an email to the recipient. We're setting the additional_headers
parameter to a string that includes the Content-Type
header, which specifies the attachment, and the Content-Disposition
header, which specifies the file name and disposition.
The Content-Type
header should be set to text/plain
for a PDF attachment, and the Content-Disposition
header should be set to attachment
to indicate that the file is an attachment.
You can also use the mime_content_type()
function to specify the MIME type of the attachment:
$headers.= 'Content-Type: application/pdf; name="'. $pdf_name. '"'. "\r\n";
This will set the MIME type of the attachment to application/pdf
.
You can also use the fp_fopen()
and fp_read()
functions to read the PDF file and attach it to the email:
$pdf_file = 'path/to/example.pdf';
$pdf_name = 'example.pdf';
// Open the PDF file
$pdf = fopen($pdf_file, 'rb');
// Read the PDF file
$pdf_content = fread($pdf, filesize($pdf_file));
// Close the PDF file
fclose($pdf);
// Set the email headers
$headers = 'From: [email protected]'. "\r\n".
'Reply-To: [email protected]'. "\r\n".
'Content-Type: application/pdf; name="'. $pdf_name. '"'. "\r\n".
'Content-Disposition: attachment; filename="'. $pdf_name. '"';
// Set the email body
$body = $message;
// Send the email
mail($to, $subject, $body, $headers, $pdf_content);
In this example, we're using the fp_fopen()
and fp_read()
functions to read the PDF file and attach it to the email. We're setting the Content-Type
header to application/pdf
and the Content-Disposition
header to attachment
to indicate that the file is an attachment.
Note that you should replace the path/to/example.pdf
with the actual path to your PDF file.