Send HTML emails using PHP’s mail() function
I’ll start with mail(), as it’s a native function in PHP. With it, you can send plain text and simple HTML emails. First, I’ll list its limitations and then provide code pieces for sending HTML emails.
Limitations of PHP mail() function
PHP mail function might be simple, but there are several things it won’t allow you to do:
- You won’t be able to add attachments without complex configurations;
- You won’t be able to embed images directly within the email as attachments that can be referenced in the HTML content via CID (Content ID);
- You’ll have trouble sending emails to multiple recipients as the mail() function opens and closes the SMTP socket for each sent email. This can be time-consuming and resource-intensive.
- You’ll have trouble connecting to third-party SMTP servers as the mail() function sends emails over the local server. And, for the same reason, you’ll most likely encounter deliverability issues (even if you’ve correctly configured SPF, DKIM, and DMARC and followed deliverability best practices).
Considering the limitations and security concerns, mail() function isn’t a preferable option to send emails from PHP. But, if you still want to use it, I’ll show you how in the next section. Read this blog post or watch this video for a detailed overview of sending emails in PHP.
Send a simple HTML email
The built-in mail() function requires four arguments: the recipient’s email address, the subject of the email, the message, and additional headers. The additional headers allow us to set the Content-type header and specify it as text/html.
Sometimes, extra headers are used to specify the 'X-Mailer: PHP/' . phpversion() header. This can be useful for debugging but could reveal your server configurations. For that reason, I decided to omit it.





















