Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Sending Emails in PHP Using Mail() Function

March 10, 2016

5 Min Read
Reading Time: 5 minutes

Email is the preferred method of modern business communication. In today’s era of science and technology, emails are the fastest and most reliable communication channel. Hence, for immediate correspondence in the corporate world, emails are very significant.

Another benefit of emails is the ease of record keeping. Emails are kept in the inbox until deleted.

In the field of internet marketing, email marketing is still an effective approach. The cost factor is also very significant in business communication. You may simply sign up for free on Yahoo!, Outlook and Gmail and start communicating easily.

php send email

Sending email in PHP is necessary for a professional approach. Its significance is greater in sales and marketing. No matter what your business model is, you will have to send and receive emails in B2B, B2C or C2C business models.

What Are the Options to Send Emails in PHP?

PHP is a widely used server side scripting language. It provides many built-in functions which we call predefined functions of PHP. PHP provides email support via a built-in mail() function. Using this function, you can easily send emails directly through your PHP script. Alternatively you may use the phpmailer library to send emails. Check out this tutorial on phpmailer example to see how to use this library. In this post we will discuss the PHP mail() function.

Email Syntax:

mail (to,subject,message,headers,parameters);

Give Your PHP Applications Optimum Web Performance

Host Your PHP Apps With Us & See The Blazing Web Performance Yourself!

Email Parameters:

The following are the email parameters in PHP.

To:

The first parameter which we have in email () function is ‘to’. It is a mandatory parameter. You will have to give receiver’s email id with this parameter.

Subject:

It is also a mandatory field. It must be specified with the subject of the email. It can’t contain newline characters.

Message:

This field is also not optional. Message parameter has character limit of 70 characters so it should not exceed the limit. Moreover, the lines should be separated by (\n).

Headers:

It is used to specify additional headers like BCC and CC. They must be separated by (/r/n). Form header is essential in sending emails. It is set with this parameter or by php.ini file.

Parameters:

It can be used to set additional parameter like setting envelope sender address.

You might also like: PHP 7.1 Powered Hosting Now Available On Cloudways

PHP Mail() Example: Email form

Let’s consider a practical use of the mail() function in this PHP mail() example. Below is the Email sending form which you may have to coordinate with your users. You may use this form for receiving inquiries from your clients, whether you are have an Ecommerce platform, B2B website or a B2C website.

Email Form
In the above form, every field is validated using validation functions. The fields are filled using isset() function to ensure every field is filled. Let’s discuss every field one by one:

First of all, you have first name and last name fields. It is validated using preg_match() function as well. Both these fields are also validated using HTML validations in terms of maximum limit of characters. You can set this limit according to your ease.

Next, we have email address field where the user specifies his email address. When we refer to the mail() function, this field is respective to From parameter. Its maximum characters limit is also set using HTML validation . Also it is passed through preg_match() test.

Then we have the telephone number field which is the only optional field in our form. The user may give his telephone number for future correspondence. We have used HTML validation here in terms of maximum limit which is set to 30 characters. You may set this limit according to your regional numbers.

In the comments section, you may enter your message for the receiver or webmaster. It is also validated using HTML validation. Again you can set your limit as you need; we have set this limit to 80.

You might also like: How To Send Emails In PHP Using PHPMailer Library

Below are few snapshots of the operations of above form:

1. When form is submitted blank

email form22. When every field is submitted correctly, a message will appear as below

email form3

3. In the webmaster’s inbox, a message will be delivered as below

Email Inbox

Source Code:

Here is the code of our email_form.php

<?php

if(isset($_POST['email'])) {

$email_to = "atif.shahab@cloudways.com";

$email_subject = "Summarized propose of the email";

//Errors to show if there is a problem in form fields.

function died($error) {

    echo "We are sorry that we can procceed your request due to error(s)";

    echo "Below is the error(s) list <br /><br />";

    echo $error."<br /><br />";

    echo "Please go back and fix these errors.<br /><br />";

    die();

}

// validation expected data exists

if(!isset($_POST['first_name']) ||

       !isset($_POST['last_name']) ||

       !isset($_POST['email']) ||

       !isset($_POST['telephone']) ||

       !isset($_POST['comments'])) {

    died('We are sorry to proceed your request due to error within form entries');   

}

$first_name = $_POST['first_name']; // required

$last_name = $_POST['last_name']; // required

$email_from = $_POST['email']; // required

   $telephone = $_POST['telephone']; // not required

$comments = $_POST['comments']; // required

$error_message = "";

$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

 if(!preg_match($email_exp,$email_from)) {

$error_message .= 'You entered an invalid email<br />';

 }

$string_exp = "/^[A-Za-z .'-]+$/";

 if(!preg_match($string_exp,$first_name)) {

$error_message .= 'Invalid first name<br />';

 }

 if(!preg_match($string_exp,$last_name)) {

$error_message .= 'Invalid Last name<br />';

 }

 if(strlen($comments) < 2) {

$error_message .= 'Invalid comments<br />';

 }

 if(strlen($error_message) > 0) {

   died($error_message);

 }

$email_message = "Form details below.\n\n";

function clean_string($string) {

  $bad = array("content-type","bcc:","to:","cc:","href");

  return str_replace($bad,"",$string);

}

$email_message .= "First Name: ".clean_string($first_name)."\n";

$email_message .= "Last Name: ".clean_string($last_name)."\n";

$email_message .= "Email: ".clean_string($email_from)."\n";

$email_message .= "Telephone: ".clean_string($telephone)."\n";

$email_message .= "Comments: ".clean_string($comments)."\n";

// create email headers

$headers = 'From: '.$email_from."\r\n".

'Reply-To: '.$email_from."\r\n" .

'X-Mailer: PHP/' . phpversion();

@mail($email_to, $email_subject, $email_message, $headers);

?>

<!-- include your own success html here -->

Thank you for contacting us. We will be in touch with you very soon.

<?php

}

?>

<form name="contactform" method="post" action="email_form.php">

<table width="450px">

<tr>

<td valign="top">

 <label for="first_name">First Name *</label>

</td>

<td valign="top">

 <input  type="text" name="first_name" maxlength="50" size="30">

</td>

</tr>

<tr>

<td valign="top"">

 <label for="last_name">Last Name *</label>

</td>

<td valign="top">

 <input  type="text" name="last_name" maxlength="50" size="30">

</td>

</tr>

<tr>

<td valign="top">

 <label for="email">Email Address *</label>

</td>

<td valign="top">

 <input  type="text" name="email" maxlength="80" size="30">

</td>

</tr>

<tr>

<td valign="top">

 <label for="telephone">Telephone Number</label>

</td>

<td valign="top">

 <input  type="text" name="telephone" maxlength="30" size="30">

</td>

</tr>

<tr>

<td valign="top">

 <label for="comments">Comments *</label>

</td>

<td valign="top">

 <textarea  name="comments" maxlength="1000" cols="25" rows="6"></textarea>

</td>

</tr>

<tr>

<td colspan="2" style="text-align:center">

 <input type="submit" value="Submit">  </a>

</td>

</tr>

</table>

</form>

The only drawback with this function is that you can’t send emails via local host through this mail() function.

Better Customer Service

As you have seen, the use of mail() functions enables you to get inquiries from your customers directly into your inbox. Hence you can provide better services by keeping your clients issues on record and then resolve them for better community feedback. We can address the drawback which is mentioned above by adopting an alternative approach to send email in PHP. We will discuss the alternative approach in part 2 of our sending email in PHP. If you have any questions about this PHP mail() example, leave a comment and I’ll get back to you.

To test out the mail() function, launch your free trial of Cloudways Managed PHP Hosting Platform. You will be impressed by the amazing speed of PHP 7 combined with our optimized stack, which can give a huge boost to your online business. If you have any questions about the services, contact our 24/7/365 Live Chat Support Team.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Ahmed Khan

Ahmed was a PHP community expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is a software engineer with extensive knowledge in PHP and SEO. He loves watching Game of Thrones is his free time. Follow Ahmed on Twitter to stay updated with his works. You can email him at ahmed.khan@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!