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

Introduction to email function in PHP

We see websites having links to contact by way of Contact Us or An Inquiry form or some other way. After clicking the contact link, the visitors are presented with a form asking for information followed by a Submit button. Generally, an email is sent to the webmaster or contact persons of that website.

In your PHP based website, you will need to give “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 the PHP mail() function.

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

Syntax of the mail function()

mail (to, subject, body, headers)

A very simple example of PHP send email can be:

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

All parameters are self-descriptive.

The headers is an optional parameter. It specifies information like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n).

A working example of sending simple text PHP email

Let us first create a simple interface for the user to write the email message in HTML for our PHP email example.

Name this file as testemail.html.

Now create another file, sendemail.php as mentioned in the form: method = “sendemail.php” in our HTML email form.

Step 2: The send email script

Place the following code in sendemail.php in order to PHP email function work:

If email is sent properly, the following will be the 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 a few additions. See the example below.

For simplicity purpose, form to send input information remains the same as in above example. Only code in the 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

Note: You just have to specify in headers to send an email as HTML.

How to validate email address using PHP

PHP provides a very simple built-in filter for validating email address:


PHP email validation by FILTER_VALIDATE_EMAIL example

We will use the previous example of HTML email and just place a piece of code for email validation whether email entered from HTML page was valid or not. If it is not valid the script will display email not valid message and stops processing further.

So in the above example, if a user has entered an invalid email address like yourmail@gmail or or missed the required format it will show “Email is not valid” as output by using PHP email validate function.

This piece of code in the above example will handle email validation: