How can one include file attachments in emails using PHP?

To include file attachments in emails using PHP, you can use the PHPMailer library. This library allows you to easily add attachments to your emails by specifying the file path and name. You can also set the MIME type of the attachment to ensure it is properly handled by the email client.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

// Create a new PHPMailer instance
$mail = new PHPMailer();

// Set up the SMTP server settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Set the sender and recipient of the email
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('to@example.com', 'Recipient Name');

// Add attachments to the email
$mail->addAttachment('/path/to/file.pdf', 'File.pdf');

// Set the email subject and body
$mail->Subject = 'Email with Attachment';
$mail->Body = 'Please find the attached file';

// Send the email
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}