In the context of PHP programming, what are the advantages and disadvantages of manually handling email attachments versus using third-party libraries or tools?
When working with email attachments in PHP, manually handling attachments can give you more control over the process but can be time-consuming and error-prone. On the other hand, using third-party libraries or tools can simplify the task and offer additional features, but you may have less control over the implementation.
// Example of manually handling email attachments in PHP
$to = "recipient@example.com";
$subject = "Test Email with Attachment";
$message = "This is a test email with attachment.";
$attachment = "/path/to/file.pdf";
$filename = "file.pdf";
$file_contents = file_get_contents($attachment);
$attachment_encoded = chunk_split(base64_encode($file_contents));
$boundary = md5(uniqid(time()));
$headers = "From: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";
$body = "--{$boundary}\r\n";
$body .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";
$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$body .= $message . "\r\n";
$body .= "--{$boundary}\r\n";
$body .= "Content-Type: application/pdf; name=\"{$filename}\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"{$filename}\"\r\n\r\n";
$body .= $attachment_encoded . "\r\n";
$body .= "--{$boundary}--";
mail($to, $subject, $body, $headers);