Gibt es bewährte Methoden oder Best Practices, um Dateianhänge in PHP-E-Mails zu verarbeiten?

When sending emails with file attachments in PHP, it is recommended to use the PHPMailer library, which provides a more robust and secure way to handle attachments. This library simplifies the process of adding attachments to emails and ensures that they are handled correctly 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 email parameters
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Email with Attachment';
$mail->Body = 'This is a test email with attachment';

// Add the attachment
$file_path = 'path/to/attachment.pdf';
$mail->addAttachment($file_path);

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