How to attach pdf file in mail using php

To attach a PDF file to an email using PHP, you can use the mail() function or a PHP email library such as PHPMailer. Here's an example of how to do it using the mail() function:

<?php

// Set the email headers
$headers = 'From: [email protected]'. "\r\n".
           'Reply-To: [email protected]'. "\r\n".
           'MIME-Version: 1.0'. "\r\n".
           'Content-Type: multipart/mixed; boundary="===============1234567890=="';

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

// Set the PDF file to attach
$pdf_file = 'path/to/your/pdf/file.pdf';

// Open the PDF file
$pdf = fopen($pdf_file, 'rb');

// Read the PDF file contents
$pdf_contents = fread($pdf, filesize($pdf_file));

// Close the PDF file
fclose($pdf);

// Set the attachment
$attachment = 'Content-Type: application/pdf; name="'. $pdf_file. '"'. "\r\n".
              'Content-Transfer-Encoding: base64'. "\r\n".
              'Content-Disposition: attachment; filename="'. $pdf_file. '"'. "\r\n".
              "\r\n". $pdf_contents. "\r\n";

// Set the email message
$message = 'This is the email message'. "\r\n".
           '---------------------------'. "\r\n".
           $attachment. "\r\n".
           '---------------------------'. "\r\n".
           $body;

// Send the email
mail('[email protected]', 'Subject', $message, $headers);

?>

This code sets the email headers, body, and attachment, and then sends the email using the mail() function.

Alternatively, you can use a PHP email library such as PHPMailer, which provides a more robust and flexible way of sending emails with attachments. Here's an example of how to do it using PHPMailer:

<?php

require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();

$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');

$mail->Subject = 'Subject';
$mail->Body = 'This is the email body';

$pdf_file = 'path/to/your/pdf/file.pdf';
$mail->addAttachment($pdf_file, 'application/pdf', 'base64', $pdf_file);

$mail->send();

?>

This code sets up a PHPMailer object, sets the email headers and body, and then adds the PDF file as an attachment using the addAttachment() method. Finally, it sends the email using the send() method.

Make sure to replace the placeholders ([email protected], your-password, path/to/your/pdf/file.pdf, etc.) with your actual email credentials and file path.