What are the best practices for handling different email parts (plaintext, HTML) in PHP?
When sending emails in PHP, it's important to handle both plaintext and HTML versions of the email to ensure compatibility across different email clients. One common approach is to create a multipart email with both plaintext and HTML parts. This allows the recipient's email client to choose the appropriate format based on its capabilities.
// Create a boundary for the multipart email
$boundary = md5(uniqid(time()));
// Set the headers for the email
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"".$boundary."\"\r\n";
// Create the plaintext and HTML parts of the email
$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 plaintext version 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 .= "<html><body><p>This is the <b>HTML</b> version of the email.</p></body></html>\r\n\r\n";
$message .= "--".$boundary."--";
// Send the email
mail('recipient@example.com', 'Subject', $message, $headers);