How to Send HTML Email in PHP

On daily basis people receive newsletter emails that are in rich HTML format. Those emails are not handwritten by a person and sent to all recipients by a person manually. That is the magic of PHP HTML email. In this tutorial we will learn how to send an HTML email through PHP mail feature.

Step # 1 – Mail function

To send a PHP mail we need to know one important function in PHP, the mail() function. The mail() function takes in four arguments; first is the recipient email address, second is the subject of the mail, third is the actual message, and the final argument is a header that specifies the sender’s address and the content type. The header can also include carbon copy recipients.

The mail function

Step # 2 – Setting basic parameters

We will begin setting up our email by specifying the “to”, “from”, and the “subject” variables, by assigning them with the recipient address, our own address, and the subject of our email. Next we will assign the “from” to the header along with declaring the content type as text and HTML.

Defining parameters before adding the message

Step # 3 – Creating the email and sending

On to the most important part of the email, we need to write a full HTML based message that will follow the same syntax as that of any HTML document. The “message” variable is instructed to include all text and lines until it reaches the EOF or the end of file code. Once the message and its Meta-information is set, we should use the PHP mail function to send the email and return a confirmation to the user.

Adding the message and a confirmation response

And that’s all about PHP HTML email.