Php html email html multipart

A classic topic!

When sending an email with HTML content using PHP, you'll often need to use a technique called "Multipart/Alternative" to ensure that the email is displayed correctly in different email clients.

Here's a brief overview:

What is Multipart/Alternative?

Multipart/Alternative is a way to send an email with multiple parts, each with a different content type. In this case, you'll have two parts:

  1. Text part: a plain text version of the email, which is used as a fallback for email clients that don't support HTML.
  2. HTML part: the HTML version of the email, which is used for email clients that support HTML.

Why do I need Multipart/Alternative?

Email clients like Gmail, Outlook, and Yahoo Mail may not always display HTML emails correctly. Some may strip out HTML tags, while others may not support certain HTML features. By sending a plain text version of the email, you ensure that the message is still readable even if the HTML version is not displayed correctly.

How do I create a Multipart/Alternative email in PHP?

Here's an example code snippet that demonstrates how to create a Multipart/Alternative email using PHP:

<?php

// Set the email headers
$headers = array(
    'From' => 'Your Name <[email protected]>',
    'Reply-To' => 'Your Name <[email protected]>',
    'Subject' => 'Test Email with HTML',
    'MIME-Version' => '1.0',
    'Content-Type' => 'multipart/alternative; boundary="===============1234567890=="'
);

// Set the email body
$body = array();

// Text part
$text_part = "This is a plain text version of the email.";
$body[] = "Content-Type: text/plain; charset=UTF-8\r\n\r\n$text_part";

// HTML part
$html_part = "<html><body>This is an HTML version of the email.</body></html>";
$body[] = "Content-Type: text/html; charset=UTF-8\r\n\r\n$html_part";

// Combine the email body parts
$email_body = implode("\r\n--===============1234567890==--\r\n", $body);

// Send the email
mail('[email protected]', 'Test Email with HTML', $email_body, $headers);

?>

In this example, we create an array of email body parts, each with a different content type:

  1. The first part is a plain text version of the email (text/plain).
  2. The second part is an HTML version of the email (text/html).

We then combine the email body parts using the implode() function, separating each part with a boundary string (--===============1234567890==--). This boundary string is used to separate the different parts of the email.

Finally, we send the email using the mail() function, passing in the email body and headers.

Tips and Variations