How to attach a pdf file to php mail

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

<?php
// Define the email variables
$to = '[email protected]';
$subject = 'Email with attachment';
$message = 'This is the message body';

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

// Define 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="This is the boundary string"';

// Create the email body
$email_body = "This is the email body\r\n\r\n";
$email_body.= "--This is the boundary string\r\n";
$email_body.= "Content-Type: application/pdf\r\n";
$email_body.= "Content-Disposition: attachment; filename=\"$pdf_file_name\"\r\n";
$email_body.= "Content-Transfer-Encoding: base64\r\n";
$email_body.= "\r\n";
$email_body.= chunk_split(base64_encode(file_get_contents($pdf_file)));
$email_body.= "--This is the boundary string--";

// Send the email
mail($to, $subject, $email_body, $headers);
?>

In this example, we're using the mail() function to send the email. We're defining the email variables, the PDF file path and name, and the email headers. We're then creating the email body by concatenating the message body, the boundary string, and the PDF file contents.

The chunk_split() function is used to split the base64 encoded PDF file contents into smaller chunks to avoid email client issues. The base64_encode() function is used to encode the PDF file contents in base64 format.

You can also use PHPMailer library to send the email with attachment. Here's an example:

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

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

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

$mail->Subject = 'Email with attachment';
$mail->Body = 'This is the message body';

$pdf_file = 'path/to/your/pdf/file.pdf';
$pdf_file_name = 'your_pdf_file.pdf';

$mail->addAttachment($pdf_file, $pdf_file_name, 'application/pdf');

if (!$mail->send()) {
    echo 'Error sending email: '. $mail->ErrorInfo;
} else {
    echo 'Email sent successfully';
}
?>

In this example, we're using the PHPMailer library to send the email. We're defining the email variables, the PDF file path and name, and the email settings. We're then adding the PDF file as an attachment using the addAttachment() method.

Make sure to replace the placeholders with your actual email settings and PDF file path.