Are there any recommended libraries or frameworks for handling file attachments in PHP emails?
When sending emails with file attachments in PHP, it is recommended to use a library or framework that simplifies the process. One popular library for handling file attachments in PHP emails is PHPMailer. PHPMailer provides easy-to-use methods for adding attachments to emails and ensures that the attachments are properly encoded and sent with the email.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$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 = 'Please see the attached file.';
$mail->addAttachment('path/to/file.pdf', 'filename.pdf');
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Email could not be sent. Mailer Error: ', $mail->ErrorInfo;
}