The PHP mail function: description, application features

Table of contents:

The PHP mail function: description, application features
The PHP mail function: description, application features

Building a website can be the start of a big project, and choosing the right customer feedback technology is the key to success. Web developers often use the PHP Mail function to send email. The most convenient way to do this is when a site visitor fills out a form.

History of PHP technologies

History of PHP technologies
History of PHP technologies

They are used to develop web applications. These technologies appeared by chance, like many other great discoveries. Rasmus Lerdorf was looking for a solution to the overload problem on the server where he hosted his personal page and curriculum. This led to the creation of PHP (Personal Home Page) in 1994. In 1995 Rasmus released the source code and created a mailing list to exchange ideas, improvements, fixes. Since then, the language has grown and developed as an open source project.

In 1996, just a year after its publication, it was already being used on 15,000 websites. In 1998, his Internet presence was almost 60,000 domains, about 1% of the total number of existing projects and blogs. ATPHP is currently used by approximately 24% of all existing web projects in the world.

PHP Mail function
PHP Mail function

This popularity of the model is caused not only by quality, but also by the importance of feedback. Sites that use this technology today include WordPress, Twitter, and Facebook. Therefore, the evolution of PHP to meet the hypertext preprocessor is undoubtedly exponential in every way.

Project with self-installing packages

PHP is a free and open language with a low learning curve, its syntax is simple and follows the basic standards of object-oriented programming. Complex development environments are not required, as well as time for education. Programming is self-guided, all available IDEs are free, and development is quick and easy to set up.

Deploying a project in PHP is easy because it has self-integration packages that use: Apache and MySQL for both UNIX (LAMPP) and Windows (XAMPP). Both are easy to install and set up as a desktop application. The user gets a local server with access to the database on the computer, ready to develop any project. No time wasted on compatibility issues. In addition, it offers easy access to databases and supports many formats, not just MySQL.

Below is the code for the basic email function. You can script and use the form on any website by setting variables to send such an email.

Project with self-installing packages
Project with self-installing packages

The first part of the form checks if the email address field is filled in. If it is not, an HTML form is displayed on the page. If an online email is prepared, after the visitor completes the form, it is ready to be sent. When the Submit button is clicked, the page reloads, PHP checks if an email address has been entered and submits the document.

Popular Mail Library

There are many ways to deliver letters. Usually email is sent in two ways:

  • using PHP's built-in Mail function;
  • using a third party library such as PHPMailer with SMTP.

Before you start using the program, you will need the following:

  1. Web hosting.
  2. Email account.
  3. Enabled PHP Mail function.
  4. SMTP function enabled.
  5. Domain from Hostinger MX record.

Mail in PHP allows you to send email using the local sendmail program. Each time the user starts the mail service, he invokes this local program, usually configured by the system administrator. You can enable or disable this feature in the "E-mail" section -> "Mail Service Management Section".

PHPMailer is a popular library that supports sending mail via the PHP Mail or SMTP function.

Send method in PHP based environment
Send method in PHP based environment

Working algorithm:

  1. To use PHPMailer with Hostinger SMTP, you first need to create an ID inthe "Email Account" section of the web hosting panel. The user will have four fields: email account username, password, SMTP host, SMTP port.
  2. After that, the installation of PHPMailer starts. One easy way to do this is to use Composer, which is pre-integrated into shared hosting plans, so connect via SSH and run the following command: cd public_html.
  3. Next run: composer requires phpmailer and wait a few minutes for the installation to complete and PHPMailer to appear in the created vendors directory. SMTP is used for delivery. This line imports the PHPMailer class into the global namespace and includes various libraries.
  4. Send an HTML message. Its contents will be taken from the message.html file located in the same directory. This allows text formatting and more functionality than regular text messages.

Run script

PHPMailer offers the user additional features that can be tried in the official GitHub repository. Also, if he is using WordPress, he can easily create a contact form using plugins.

Contact form with plugins
Contact form with plugins

Use PHPMailer for more than just sending messages. You can create a contact form where visitors or users contact the site. Below is the end result of creating the form.

Form creation result
Form creation result

Script launch order:

  1. Create a filetestphpmailer.php and fill in the SMTP fields that were received earlier.
  2. Execute the script by typing in the browser, a message will appear.
  3. Once the user submits it, they will receive confirmation that the content will be delivered to the email address specified in the Address field.
  4. If the PHPMailer contact form is not working, to test the PHP Mail function add the following line to find out the cause of the problem: $ mail-> SMTPDebug=2.


Troubleshooting Common Errors
Troubleshooting Common Errors

PHPMailer is a fairly easy tool to learn. But from time to time errors can occur, and then the Mail PHP function does not work.

Common problems when sending mail:

  1. Sender address rejected - error means that the server was unable to authenticate using the provided data. To fix it, parse the from headers and make sure they match the existing mailbox. Once eliminated, the script will start executing.
  2. Gmail cannot confirm that sent the message - warning when testing PHP mail script. Indicates that the SPF record is not enabled, the email address does not exist, or does not belong to the user.
  3. DNS failures - often seen as connection timeouts: "Temporary failure in name resolution", "Unable to resolve host", "getaddrinfo failed" or similar errors.
  4. Firewall redirect. This is related to Google and if the user sees somethinglike the ISP name, then there are authentication and TLS certificate verification errors.
  5. SELinux blocking - prevents PHP or webserver from sending email, likely on RedHat/Fedora/Centos.

Parsing JSON with PHP

Parsing JSON with PHP
Parsing JSON with PHP

JSON support in PHP is extremely simple, with only one common library to handle data conversion from PHP arrays and objects. It is rapidly gaining popularity due to its readability, portability, and the ability to be used in web browsers without additional databases. If the user is wary of XML, JSON, this is the best direction for him.

With XML, it is more comfortable to work with user data directly in the XML parser you are using. With JSON, you can immediately convert data into a PHP object or array and work with it using familiar PHP structures, control flow, and functions.

The first thing the application needs to do is check the Mail PHP function to see if the error code it received is what it expected. For a simple GET request, the response should be 200 if it was successful.

To get the status code using Json decode, where $ return represents the content returned from the API request, $ code will be set to 200. The second argument in the Mail PHP Json decode post function returns the result as an associative array, and not an object.

An even better way to check for an error is to do the following:

$json=json_decode($return, true);


$json=json_decode($return, true);


It is very important that the code is set up to properly handle and account for all errors. But even if the request is formed correctly, there is still a chance that the user will receive an error code when executing it.

Post project advantage

Post project advantage
Post project advantage

For a programmer who wants to learn PHP, the programming language offers huge benefits. It has perhaps one of the largest online communities in comparison with others, and it is within the framework of this support that almost any problem is solved.

For each user of PHP, its capabilities are important not only in the current network, but also in the future. From the point of view of experts, if this technology continues its current pace of development, adapting to new needs and adding more features, it has a future.

PHP Benefits:

  1. The language is completely free and open.
  2. Very low learning curve.
  3. Development environments are quick and easy to set up.
  4. Easy deployment: fully self-installing packages with PHP integration.
  5. Easy access to databases.
  6. Very large community.

PHP technology is interesting and essential for many of the most common tasks associated with sending email and using attachments.

Popular topic

Editor's choice

  • Restore Skype account: step by step instructions, return access to your account
    Restore Skype account: step by step instructions, return access to your account

    Don't know how to recover your Skype account? Or do you want to know your friend's Skype password? The article discusses several ways to restore the user's page, as well as recommendations for storing and selecting pin codes

  • Why can't I follow on Instagram? All possible reasons
    Why can't I follow on Instagram? All possible reasons

    We subscribe to people with a specific goal - to find friends, like-minded people of interest, to learn something new for ourselves. And sometimes it is very strange to see that the Instagram system does not allow you to "follow" the profile you are interested in. This error occurs quite often, no one is immune from this trouble. Let's analyze the main reasons why Instagram does not allow you to subscribe to people

  • How to find out who "liked" a person on Instagram. Proven Methods
    How to find out who "liked" a person on Instagram. Proven Methods

    Everyone who is trying to start the path of a blogger or has already achieved some success in this field, hopes that the content that he shares with readers will not be left without attention. The main indicator of page popularity is “likes”. “Thumbs up” is also put when they want to attract the attention of potential subscribers

  • How to restore a channel on YouTube: detailed instructions, simple and effective tips
    How to restore a channel on YouTube: detailed instructions, simple and effective tips

    This article describes how to restore a channel on YouTube after deleting it. To understand this task, it will be useful to familiarize yourself with some terminology. There is a difference between deleting and blocking a YouTube account

  • How to remove a contact from "Vatsap" and how to block an unwanted interlocutor
    How to remove a contact from "Vatsap" and how to block an unwanted interlocutor

    WhatsApp is a popular messenger. It has many features that users are not even aware of. One of these is the ability to block contacts. It helps to get rid of annoying interlocutors. And how to remove a contact from WhatsApp and how to block it? You can perform these actions in different ways