In previous examples we have seen how we could send an email in PHP and how we could add a different recipient for the response. Although, in both cases, the email sent was an email in text format. In this example we are going to see how we can send email with HTML in PHP.
When sending email formatted HTML in PHP we can increase the possibilities of its visualization in the email clients of our recipients. This way we can insert images, tables, forms,…
The first thing will be to configure the email recipient.
$para = '[email protected]';
Then we will define a variable for the title and another for the content. In this case the text that we insert in the content will already be pure HTML.
$titulo = 'Sending email from PHP';
$message = '<html>'.
'<head><title>Email with HTML</title></head>'.
'<body><h1>Email with HTML</h1>'.
'This is an email that is sent in HTML format.'
'<hr>'.
'Sent by my PHP program'.
'</body>'.
'</html>';
We can use any element HTML that we want and we can even add CSS content. Although it must be taken into account that some email clients are very limited when it comes to viewing the content of the emails. That is why it is not highly recommended to abuse the features, especially those of CSS.
This will not be enough to be able to send email formatted HTML at HTML. We still have to do something else, this will be to add some headers in which we say that the content we are sending is a HTML.
These headers indicate that the MIME-Version is 1.0, that the content-type is "text/html" and that the encoding charset is "utf-8" or another one you want to use.
$headers = 'MIME-Version: 1.0' . "rn"
$headers .= 'Content-type: text/html; charset=utf-8' . "rn";
It is important not to forget that the headers are separated by lines using a CRLF code (rn).
We will only have to add the header to indicate who we are (those who sent the email):
$headers .= 'From: My Name';
And send the email using the mail() function.
$sent = mail($to, $title, $message, $headers);
if ($sent)
echo 'Email sent successfully';
else
echo 'Error sending email';
With this we will have managed to send email in HTML in PHP.
