How to enable html in mail function inphp
To enable HTML in the mail()
function in PHP, you need to set the Content-Type
header to text/html
and also specify the HTML content in the email body.
Here's an example:
$headers = 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-type: text/html; charset=UTF-8'. "\r\n";
$message = '<html><body><h1>Hello World!</h1></body></html>';
mail('[email protected]', 'Subject', $message, $headers);
In this example, we're setting the Content-Type
header to text/html; charset=UTF-8
, which tells the email client to render the email body as HTML. We're also specifying the HTML content in the $message
variable.
Note that you can also use the mb_send_mail()
function, which is a multibyte-safe version of the mail()
function. It also allows you to specify the Content-Type
header and the email body as HTML.
$headers = 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-type: text/html; charset=UTF-8'. "\r\n";
$message = '<html><body><h1>Hello World!</h1></body></html>';
mb_send_mail('[email protected]', 'Subject', $message, $headers);
Make sure to check the PHP documentation for more information on the mail()
and mb_send_mail()
functions.
Also, keep in mind that some email clients may not support HTML emails, so it's always a good idea to provide a plain text alternative for those clients. You can do this by setting the Content-Type
header to multipart/alternative
and including both the HTML and plain text versions of the email body.
$headers = 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-type: multipart/alternative; boundary="MyBoundary"'. "\r\n";
$message = '--MyBoundary'. "\r\n";
$message.= 'Content-Type: text/plain; charset=UTF-8'. "\r\n";
$message.= 'Hello World!'. "\r\n";
$message.= '--MyBoundary'. "\r\n";
$message.= 'Content-Type: text/html; charset=UTF-8'. "\r\n";
$message.= '<html><body><h1>Hello World!</h1></body></html>'. "\r\n";
$message.= '--MyBoundary--';
mail('[email protected]', 'Subject', $message, $headers);
This way, email clients that support HTML emails will render the HTML version, while those that don't will fall back to the plain text version.