How to Send Emails Using PHP mail

How to Send Emails Using PHP mail

Email is an integral part of any project or business. While there are numerous business email platforms, including Hostinger, Zoho Mail, and G Suite, you can also use PHP mail. In this tutorial, we will learn how to send emails using PHP’s inbuilt mail() function and the PHPMailer with Simple Mail Transfer Protocol (SMTP).

Using PHP mail() Function

The mail() function in PHP invokes a Sendmail program, usually configured by the system administrator, that allows you to send emails.

To use the mail() function, make sure that the Sendmail service is on.

If you use Hostinger, you can enable/disable this function by accessing the hPanel, then click on Emails -> Mail Service Control.
The mail service control option on hPanel

By default, the Sendmail service is already enabled. Nonetheless, you should check it to be sure.
The Sendmail service option is enabled by default

Creating a Test File for PHP Mail

First of all, you need to create a file for the PHP mail script and place it in the public_html directory so that it can be easily accessed through the domain name.

  1. Access the hPanel, click on the File Manager -> Go to File Manager.
    The File Manager on hPanel
  2. Create a new file by clicking on Add New. Let’s name the file testmail.php, then Press Create.
    Create a testmail.php file in your Public_html.
  3. Double click on the testmail.php file to edit its function using PHP. Here is an example of the basic components of PHP mail we use for this tutorial (will be explained in the next section). Click Save & Close when you’re done editing.
    Here is an example of the basic components of PHP mail.
  4. Now, you can send an email by accessing YourDomain/testmail.php from the browser. Keep in mind that you must change YourDomain to the domain you use to create testmail.php. In this example, we send the email by accessing
    send a PHP mail by accessing your domain
  5. The target email will receive the message you sent!
    A target email inbox receiving the test email.

Understanding PHP Mail Components

As mentioned before, we will introduce you to the components of a basic PHP mail script. On this occasion, we have provided a basic email syntax to help you understand better.

However, if you need more information about the Sendmail function and its components, you can refer to the official PHP documentation.

Here is the PHP syntax we use in the previous section:

    ini_set( 'display_errors', 1 );
    error_reporting( E_ALL );
    $from = "";
    $to = "";
    $subject = "Checking PHP mail";
    $message = "PHP mail works just fine";
    $headers = "From:" . $from;
    mail($to,$subject,$message, $headers);
    echo "The email message was sent.";

let’s break it down:

ini_set( 'display_errors', 1 );
error_reporting( E_ALL );

These first two lines enable error reporting. They will tell you if the script fails to execute.

$from = "";

The above line should contain the sender’s or your email address. Most hosting providers don’t allow random email addresses here, as it can be used for spoofing. Use one that is created for your domain name or brand to execute the PHP mail successfully.

$to = "";

The line is where you insert the recipient’s email address.

$subject = "Checking PHP mail";

It’s the field to enter the subject of your email message.

$message = "PHP mail works just fine";

The component above is where you can type in your message.

$headers = "From:" . $from;

It specifies vital information, such as the sender address, the reply-to location, etc.

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

The function executes PHP mail.

echo "The email message was sent.";

The message above will appear once the script executes.

Using PHPMailer to Send Emails

PHPMailer is a popular mail sending library for PHP. It supports mail sending via mail() function or Simple Mail Transfer Protocol (SMTP). This library simplifies the complicated process of building a PHP mail by providing a set of functions to create and send an email.

Installing PHPMailer is quite simple, especially if you have installed Composer. Luckily, if you use Hostinger, you do not need to install the software since it is already pre-installed on the hosting plans.

Nonetheless, to install the PHPMailer, you need to connect your hosting account via SSH terminal. Follow these steps:

  1. Download and install PuTTY SSH Client.
  2. Go to your hPanel dashboard, find and click SSH Access under the Advanced section.
  3. Take note of the SSH Access Information. You will need the SSH IP address, port, username, and password.
  4. Open PuTTY, then set your SSH IP and port accordingly.
    PuTTY SSH configuration.
  5. Press Open and a command window will appear. Type in your SSH username and password. Note that PuTTY will NOT display your password. Do not be confused if your password does not appear on the screen. Then tap Enter.
  6. Execute the following command:
    cd public_html

    Press Enter, then run this command:

    composer require phpmailer/phpmailer
  7. Wait for a moment until the installation process finish.
    PHPMailer complete installation process

Using PHPMailer with Hostinger SMTP

Once you’ve installed the PHPMailer on your hosting, you can use it to send PHP mails using Hostinger SMTP.

That being said, follow this tutorial:

  1. Create an email account by accessing the hPanel, then go to Email Account -> Create a New Email Account. Fill in the new email address and set a password before clicking Create.
    Creating a new email account in hPanel.
  2. Once you’re done, pay attention to your SMTP details located on the same page:
    This image shows the email SMPT details.Note that you must remember the email account username, the account password, SMTP host, and SMTP port to send an email via PHPMailer.
  3. Create a testphpmailer.php file in the Public_html. Access the hPanel dashboard, then click on File Manager -> Go to File Manager.
  4. Press Add New, then name the file as testphpmailer.php and click Create.
  5. Double tap on the newly made testphpmailer.php file, then paste these lines of codes into it:
    use PHPMailer\PHPMailer\PHPMailer;
    require 'vendor/autoload.php';
    $mail = new PHPMailer;
    $mail->SMTPDebug = 2;
    $mail->Host = '';
    $mail->Port = 587;
    $mail->SMTPAuth = true;
    $mail->Username = '';
    $mail->Password = 'YOUR PASSWORD HERE';
    $mail->setFrom('', 'Your Name');
    $mail->addReplyTo('', 'Your Name');
    $mail->addAddress('', 'Receiver Name');
    $mail->Subject = 'Testing PHPMailer';
    $mail->msgHTML(file_get_contents('message.html'), __DIR__);
    $mail->Body = 'This is a plain text message body';
    if (!$mail->send()) {
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'The email message was sent.';
  6. Modify the above code accordingly. For example, you need to replace EMAIL_ACCOUNT_PASSWORD with your email password, to your username, with your recipient email address, etc. Once adjusted, click Save & Close.
  7. Your PHPMailer is now ready to use. Execute the script by entering in your browser.
    send a PHP mail by accessing your domain on a browser
  8. The receiver will get the message you sent!
    test mail received in inbox

Understanding PHPMailer Components

To understand how PHPMailer works, let’s investigate the above example script that uses SMTP for email delivery. Here is the explanation of each component:

use PHPMailer\PHPMailer\PHPMailer;

The line imports the PHPMailer class to the global namespace.

require '../vendor/autoload.php';

It’ll include various libraries that PHPMailer needs.


All these variables contain vital information, such as server details, headers, messages, attachments, and more. In short, they ensure that the sender is legit with SMTP authentication.

if (!$mail->send()) {

The component above defines what happens when the scripts execute.

echo 'Mailer Error: ' . $mail->ErrorInfo;

It’ll display an error message with an explanation when the script fails to send.

} else {

The line defines what happens if the script does execute.

echo 'The email message was sent!';

The message above will show if the email is successfully sent.

Pro Tip: The line SMTPDebug = 2; is only useful when you test a script and want to see how it works. You need to change it to SMTPDebug = 0; if you are done with the test to avoid the end-user seeing the SMTP delivery report.

If you pay attention to the above codes, you will notice that we are doing something a little different than in the first example — we are sending an HTML message rather than a plain text.

Therefore, your message will load its content from the message.html file located in the same directory (public_html).

This format gives greater functionality compared to plain text messages since HTML is highly customizable. You can use color, style, image, or even multimedia files that are usually obsolete in a plain text email.

PHPMailer Contact Form

You can use PHPMailer more than just sending out a simple PHP mail. One way you can utilize it is to create a contact form where your audience can get in touch with you.

Here is an example of the script:


use PHPMailer\PHPMailer\PHPMailer;

require 'vendor/autoload.php';

    $mail = new PHPMailer;


    $mail->Host = '';

    $mail->Port = 587;

    $mail->SMTPAuth = true;

    $mail->Username = '';

    $mail->Password = 'EMAIL_ACCOUNT_PASSWORD';

    $mail->setFrom('', 'Mr. Drago');

    $mail->addAddress('', 'Receiver Name');

    if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {

        $mail->Subject = 'PHPMailer contact form';


        $mail->Body = <<<EOT

Email: {$_POST['email']}

Name: {$_POST['name']}

Message: {$_POST['message']}


        if (!$mail->send()) {

            $msg = 'Sorry, something went wrong. Please try again later.';

        } else {

            $msg = 'Message sent! Thanks for contacting us.';


    } else {

        $msg = 'Share it with us!';



<!DOCTYPE html>

<html lang="en">


    <meta charset="UTF-8">

    <title>Contact form</title>



<h1>Do You Have Anything in Mind?</h1>

<?php if (!empty($msg)) {

    echo "<h2>$msg</h2>";

} ?>

<form method="POST">

    <label for="name">Name: <input type="text" name="name" id="name"></label><br><br>


    <label for="email">Email: <input type="email" name="email" id="email"></label><br><br>


    <label for="message">Message: <textarea name="message" id="message" rows="8" cols="20"></textarea></label><br><br>

    <input type="submit" value="Send">




Just like the previous scripts, you need to create a new file in the public_html folder (in this case, we named the file formscript.php). Then, edit the information inside the script accordingly. After that, you only need to run the script from your browser.

The result will look like this:PHPMailer interactive contact form example. Once your customer submits a message, he will get a confirmation, and the contents will arrive at the inbox of the email you entered in the field:

$mail->addAddress('', 'Receiver Name');

Pro Tip: In case the PHPMailer contact form does not work, add the following line to see what causes the issue: $mail->SMTPDebug = 2; Don’t forget to erase it or change the 2 to 0 once done!

PHPMailer offers more examples that you can try in their official GitHub repository. Also, if you are using WordPress, you can easily create a contact form with the help of plugins, such as WP Forms, Formidable Forms, or Gravity Forms.WP Forms website form builder for WordPress homepage.

Troubleshooting Common PHP Mail and PHPMailer Errors

Errors can occur from time to time while using PHP mail or PHPMailer. Let’s see the list of the most common ones and how you can fix them.

Sender Address Rejected: Not Owned by the User

The error means that the server was unable to authenticate using the provided details.

To fix it, check the email address you use to send the message and make sure it corresponds to an existing email box. If it is pointing to a wrong inbox, create or change it. Also, check that you’ve enabled your SPF record.

Gmail Couldn’t Verify That Sent This Message

If you see this warning when testing a PHP mail script, it could mean one of the following:

  • Your SPF record is not on. You can find the steps on how to add one here.
  • You send an email from an address that does not exist or does not belong to you. Make sure to use valid SMTP authentication details.

Mail Goes to the Spam Folder

There can be various reasons why a PHP mail can turn up in the spam box. Here are the common ones:

  • Misleading or spam-like subject. A few examples would be “Test,” “Hello,” “Testing,” “Urgent,” or similar. Make sure that you set a clear intent in your message subject.
  • You’re using and Incorrect sender address that invokes the security measure to filter your email as prevention from email spoofing and scams.
  • You are using spam trigger words. This category includes phrases like “great offer,” “click here,” “special promotion,” “this is not spam,” and so on. Try changing up your message content to see if that’s the case.
  • The mailing list does not have an unsubscribe button. When there are lots of people who report your emails as spam, you will find it difficult to avoid the spam filter. Having an unsubscribe button is a great way to prevent this.


Congratulations! You are now familiar with PHP mail and can use PHPMailer to send emails with SMTP authentication. Although this tutorial provides basic examples, the same syntax can be used for developing a contact form or other extensions for your website.

For more in-depth information, make sure to check out the PHPMailer project page.

Do you have any tips, tricks, or ideas to share? We are eager to hear them in the comments below!

The Author


Domantas G. / @domantas

Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.

Related tutorials


Anderson Carvalho Reply

June 13 2017

Cool article, But I have a problem with this part: 'smtp', 'host' => '', 'port' => 587, 'from' => array('address' => '', 'name' => 'You name here'), // Place things in '' ( quote ) here 'encryption' => 'tls', 'username' => 'yourUsername', // Place things in '' ( quote ) here 'password' => 'yourPassword', // Place things in '' ( quote ) here 'sendmail' => '/usr/sbin/sendmail -bs', 'pretend' => false,


    Domantas G.

    Replied on June 14 2017

    Hey, Can you elaborate?


    Domantas G.

    Replied on June 15 2017

    Hey, Can you provide more details? Do you get any errors?


Ashwin Reply

June 18 2017

Thank helped a lot......


Niroj Reply

February 23 2018

What is the SMTP Port number for Non-Secure?


    Gediminas B.

    Replied on February 27 2018

    Hello, Niroj. To keep security up to date, Hostinger only allows sending mail through secure ports. Therefore, non-secure SMTP is not supported.


Praisey Cruz Reply

October 05 2018

I actually have a question. The problem is my browser is displaying what appears to be a dialog of the SERVER/CLIENT for each step of the behind the scene processing just before the "Message sent!" message. I just want the "Message sent!" to appear. also i set $mail->SMTPDebug = 2;


    Gediminas B.

    Replied on October 08 2018

    Hello, Prasey. To disable the server-side message, you'd have to set your SMTPDebug value to 0. That way, you will only see a "Message sent!" message without any additional log information.


Lucas Reply

March 18 2019

Wow, thank you very much for the tutorials, they are very helpful.

Leave a reply




This site uses Akismet to reduce spam. Learn how your comment data is processed.

Become a part of Hostinger now!

More in Email
How to Use free Google SMTP Server
How to Use Free Google SMTP Server