PHP send email | How to use PHP mail function and validate email

Introduction to mail function in PHP

Often we see web sites having links to contact them by way of Contact Us or An Inquiry form or any other way. After clicking there visitors are presented with a form asking for information and then Submit. Generally an email is sent to webmaster or contact persons of that website. So in your PHP web site you will need to send email facility in many scenarios.

PHP provides a very simple way for developers to send email from their websites. This is accomplished by using mail() function.

In this chapter we will explain using mail function in PHP for simple text emails, for HTML emails.

Systax of PHP mail function()

mail (to, subject, body, headers)

A very simple example can be

mail ( “ “, “An Inquiry”, “Inquiry from your website”, “From:” )

All parameters are self-descriptive.

Headers is Optional parameter. It specifies information like From, Cc, and Bcc. The additional headers should be separated with a CRLF (rn)

A working example of sending simple text email

Lets first create a simple interface for user to write email message in HTML

Name it, testemail.html

Now create another file, sendemail.php as mentioned in method = “sendemail.php” in out HTML form.

Place following code in sendemail.php:

If email is sent properly following will be output.

email successfully sent

Send HTML email using mail function

In order to send an HTML formatted email, you have to specify a MIME version, content type and character set. This works like simple email with just few additions. See the example below. For simplicity form to send input information remains same. Only code in sendemail.php will be changed.

If all is set, the output will look like that:


HTML email example!

This is text entered.

[message entered in HTML form]
email successfully sent

You just have to specify in headers whether to send email as HTML.

Validating an email address

PHP provides a very simple built-in filter to validate email address:


A very simple example how you can use FILTER_VALIDATE_EMAIL

We will use previous example, of HTML email and just place a piece of code to validate whether email entered from HTML page was valid or not. If its not valid the script will display email not valid message and stops processing further.

So in above example if User has entered a wrong email address like yourmail@gmail or or missed required format it will show “Email is not valid” as output.

This code in above example will handle that

if(!filter_var($email_from, FILTER_VALIDATE_EMAIL))


exit(“E-mail is not valid”);



Was this article helpful?

Related Articles

Leave A Comment?