What is the best practice for sending multiple data outputs via email in PHP?
When sending multiple data outputs via email in PHP, the best practice is to use the MIME (Multipurpose Internet Mail Extensions) standard to format the email content. This allows you to include multiple data types such as text, HTML, and attachments in a single email. By using MIME, you can ensure that the email is properly formatted and can be easily read by the recipient.
<?php
// Set headers for MIME email
$boundary = md5(uniqid(microtime(), true));
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";
// Construct email body with multiple data outputs
$message = "--{$boundary}\r\n";
$message .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$message .= "This is the text content of the email.\r\n\r\n";
$message .= "--{$boundary}\r\n";
$message .= "Content-Type: text/html; charset=\"UTF-8\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$message .= "<p>This is the HTML content of the email.</p>\r\n\r\n";
$message .= "--{$boundary}\r\n";
$message .= "Content-Type: application/pdf; name=\"example.pdf\"\r\n";
$message .= "Content-Disposition: attachment; filename=\"example.pdf\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n\r\n";
$message .= chunk_split(base64_encode(file_get_contents('example.pdf'))) . "\r\n";
$message .= "--{$boundary}--\r\n";
// Send email
$to = 'recipient@example.com';
$subject = 'Multiple Data Outputs Email';
$body = $message;
mail($to, $subject, $body, $headers);
?>