Skip to content
PHP Logo

What is the purpose of using a boundary in HTML emails in PHP?

When sending HTML emails in PHP, using a boundary is essential to separate different parts of the email, such as the text content and any attachments. This helps the email client properly parse and display the email content. Without a boundary, the email may not render correctly or the attachments may not be included.

php
$boundary = md5(uniqid(microtime(), TRUE));

$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";

$email_message = "--{$boundary}\r\n";
$email_message .= "Content-Type: text/html; charset=\"UTF-8\"\r\n";
$email_message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$email_message .= "<html><body><h1>Hello, this is a test email!</h1></body></html>\r\n\r\n";

$email_message .= "--{$boundary}\r\n";
$email_message .= "Content-Type: application/pdf; name=\"example.pdf\"\r\n";
$email_message .= "Content-Transfer-Encoding: base64\r\n";
$email_message .= "Content-Disposition: attachment; filename=\"example.pdf\"\r\n\r\n";
$email_message .= base64_encode(file_get_contents('path/to/example.pdf')) . "\r\n\r\n";

$email_message .= "--{$boundary}--\r\n";

mail('recipient@example.com', 'Test Email with Attachment', $email_message, $headers);