How can one ensure that both HTML and plain text versions of an email are displayed correctly in different email clients?
To ensure that both HTML and plain text versions of an email are displayed correctly in different email clients, you can use a multipart MIME message. This involves creating two separate parts for the email - one in plain text and the other in HTML. Email clients that support HTML will display the HTML part, while those that do not will default to the plain text version.
$to = 'recipient@example.com';
$subject = 'Testing multipart email';
$html_message = '<html><body><h1>Hello, this is the HTML version of the email</h1></body></html>';
$text_message = 'Hello, this is the plain text version of the email';
// Create a boundary for the multipart message
$boundary = md5(time());
// Set headers for the email
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"{$boundary}\"\r\n";
// Create the multipart message
$message = "--{$boundary}\r\n";
$message .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$message .= $text_message . "\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_message . "\r\n";
$message .= "--{$boundary}--";
// Send the email
mail($to, $subject, $message, $headers);