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.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Sending Emails in PHP Using Mail() Function

Updated on December 1, 2021

6 Min Read
send-emails-php-mail-function

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.

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.

But it’s not the only external mail package for PHP. There are several popular options, such as Pear Mail and Swift Mailer. Unlike the mail() function, PHP mail libraries offer much more advanced solutions for handling emails. Explore them in the guide on sending email in PHP tailored by the Mailtrap.

Well! In this post we will discuss the PHP mail() function.

Email Syntax:

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

Host PHP Websites with Ease [Starts at $10 Credit]

  • Free Staging
  • Free backup
  • PHP 8.0
  • Unlimited Websites

TRY NOW

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

What is PHP Mail()

PHP mail is built under the PHP function that is used to send e-mails from PHP scripts. It is taken as a cost-efficient way to notify clients about important events. It allows the client to contact you through e-mail by giving a contact us form on the website that e-mails the provided content. You can utilize it to e-mail your newsletter subscribers.

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 = "[email protected]";

$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>

If you’re looking to send emails via local host with PHP, it’s important to find the best hosting for PHP that supports this functionality. The mail() function, while useful for sending emails, does have some limitations. For example, it doesn’t allow you to send emails via local host. This can be a drawback for some developers who rely on local host for their testing and development environments. By finding the best hosting for PHP, you can ensure that you have access to the features and functionality you need to develop and test your applications effectively.

Nothing as Easy as Deploying PHP Apps on Cloud

With Cloudways, you can have your PHP apps up and running on managed cloud servers in just a few minutes.

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.

– How do you check PHP mail () is working?

  • Make a php test record using an editor and save it.
  • Alter the $sender and $recipeint within the code.
  • Upload the php file to your server.
  • Access the respective php file in your browser to execute the php script.
  • The output shows either “Message accepted” or “Error: Message not accepted.”
Share your opinion in the comment section. COMMENT NOW

Share This Article

Inshal Ali

Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.

×

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

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now