How to enable html in mail function in php
By default, PHP's mail()
function does not allow sending HTML emails. To enable sending HTML emails using the mail()
function, you can use the following approaches:
Method 1: Use the Content-Type
header
You can set the Content-Type
header to text/html
to indicate that the email body contains HTML content. Here's an example:
$headers = 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-Type: text/html; charset=UTF-8'. "\r\n";
$mailBody = '<html><body>Hello, <strong>This is an HTML email!</strong></body></html>';
mail('[email protected]', 'Subject', $mailBody, $headers);
Method 2: Use the multipart/mixed
content type
You can use the multipart/mixed
content type to send a multipart email that contains both text and HTML parts. Here's an example:
$headers = 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-Type: multipart/mixed; boundary="multipart-boundary"'. "\r\n";
$mailBody = '--multipart-boundary'. "\r\n";
$mailBody.= 'Content-Type: text/plain; charset=UTF-8'. "\r\n";
$mailBody.= 'Hello, this is the plain text part.'. "\r\n";
$mailBody.= '--multipart-boundary'. "\r\n";
$mailBody.= 'Content-Type: text/html; charset=UTF-8'. "\r\n";
$mailBody.= '<html><body>Hello, <strong>This is an HTML email!</strong></body></html>'. "\r\n";
$mailBody.= '--multipart-boundary--'. "\r\n";
mail('[email protected]', 'Subject', $mailBody, $headers);
Method 3: Use a third-party library
If you're using a PHP framework or a third-party library, you may have more options for sending HTML emails. For example, you can use the SwiftMailer
library, which provides a more convenient way to send HTML emails.
Remember to check the documentation for your specific PHP version and mail server configuration to ensure that HTML emails are supported.