Home >Backend Development >PHP Tutorial >How to Send HTML Emails with PHP mail()?

How to Send HTML Emails with PHP mail()?

Linda Hamilton
Linda HamiltonOriginal
2024-11-26 02:42:09223browse

How to Send HTML Emails with PHP mail()?

Sending HTML Emails with PHP mail

You're encountering difficulties in displaying HTML content in the email body sent using the mail() function. Let's address this issue step by step.

Revisiting Your Code

In your provided code:

  • The Content-type header has been set to text/html, which is correct.
  • The $body variable contains raw HTML content.

Fixing the Code

To successfully send HTML emails, you need to:

  • Set the MIME-Version header to 1.0.
  • Encode the HTML content in UTF-8 format.

Here's a corrected version of your code:

<?php

$to = '[email protected]';

$subject = 'I need to show html';

$from ='[email protected]';

$body = '<head>
<meta http-equiv="content-type" content="text/html; charset=utf8" />
</head>
<body>
<p>

Explanation

  • We added MIME-Version: 1.0 at the beginning of the headers.
  • We enclosed the HTML content in a and structure, ensuring it's a valid HTML document.
  • The meta tag sets the character encoding to UTF-8, enabling proper display of special characters.
  • Best Practices for HTML Emails

    • Use inline CSS instead of external stylesheets.
    • Consider using tables for layout.
    • Test your emails thoroughly in different email clients.

    The above is the detailed content of How to Send HTML Emails with PHP mail()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn