How to print html page in mail php
To print an HTML page in a mail using PHP, you can use the mail()
function and set the Content-Type
header to text/html
. Here's an example:
<?php
$to = '[email protected]';
$subject = 'HTML Email';
$message = '<html>
<head>
<title>HTML Email</title>
</head>
<body>
<h1>Welcome to our email!</h1>
<p>This is an example of an HTML email.</p>
</body>
</html>';
$headers = 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-type: text/html; charset=UTF-8'. "\r\n";
$headers.= 'From: Your Name <[email protected]>'. "\r\n";
mail($to, $subject, $message, $headers);
?>
In this example, the $message
variable contains the HTML code for the email. The mail()
function is then called with the recipient's email address, subject, message, and headers.
The Content-Type
header is set to text/html
to indicate that the email contains HTML content. The charset
parameter is set to UTF-8
to specify the character encoding of the email.
When the email is sent, the recipient's email client will render the HTML content as a web page.
Note that some email clients may not support HTML emails or may render them differently. It's always a good idea to include a plain text version of the email as well, in case the recipient's email client doesn't support HTML.
Here's an updated example that includes a plain text version of the email:
<?php
$to = '[email protected]';
$subject = 'HTML Email';
$message = '<html>
<head>
<title>HTML Email</title>
</head>
<body>
<h1>Welcome to our email!</h1>
<p>This is an example of an HTML email.</p>
</body>
</html>';
$plain_message = 'This is a plain text version of the email.';
$headers = 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-type: multipart/alternative; boundary="MyBoundary"'. "\r\n";
$headers.= 'From: Your Name <[email protected]>'. "\r\n";
$body = '--MyBoundary'. "\r\n";
$body.= 'Content-type: text/plain; charset=UTF-8'. "\r\n";
$body.= 'Content-Transfer-Encoding: 7bit'. "\r\n";
$body.= $plain_message. "\r\n";
$body.= '--MyBoundary'. "\r\n";
$body.= 'Content-type: text/html; charset=UTF-8'. "\r\n";
$body.= 'Content-Transfer-Encoding: 7bit'. "\r\n";
$body.= $message. "\r\n";
$body.= '--MyBoundary--'. "\r\n";
mail($to, $subject, $body, $headers);
?>
In this example, the $plain_message
variable contains the plain text version of the email. The $headers
variable is set to multipart/alternative
, which indicates that the email contains multiple parts (in this case, a plain text part and an HTML part). The $body
variable is set to a string that contains the plain text part and the HTML part, separated by a boundary string (MyBoundary
). The mail()
function is then called with the recipient's email address, subject, body, and headers.