How to Send Emails Using PHP Mail and PHPMailer: A Complete Guide

How to Send Emails Using PHP Mail and PHPMailer: A Complete Guide

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

Using PHP mail() Function

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

To use this function, make sure that your hosting provider allows you to manage the Sendmail service option manually.

If you’re already using Hostinger, you can enable or disable this function by accessing the hPanel. Click on Emails -> Mail Service Control.

Using the Mail Service Control option on hPanel.

By default, the Sendmail service is already enabled. Nonetheless, you should double-check it to be sure.

The Manage 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. To access the hPanel, click on the File Manager -> Go to File Manager.
  2. Create a new file by clicking on Add New. Let’s name the file testmail.php and then hit Create.Create a testmail.php file in your public_html folder.
  3. Double click on the testmail.php since we’re going to edit it using the PHP mail() function. Here’s an example of the basic components of the function we’ll be using in this tutorial. These will be explained in more detail in the next section. For now, click Save & Close when you’re done editing.Example of the basic components of PHP mail.
  1. 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’ve used to create testmail.php.
  2. Your target email will receive the message you’ve sent.Your recipient's 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. For this example, we have provided a basic email syntax to help you understand this function in more detail.

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’ve used 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;
    if(mail($to,$subject,$message, $headers)) {
		echo "The email message was sent.";
    } else {
    	echo "The email message was not sent.";

Let’s break it down step-by-step:

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 = "";

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

$to = "";

Here’s where you insert your recipient’s email address.

$subject = "Checking PHP mail";

Enter the subject of your email message here.

$message = "PHP mail works just fine";

Here you can compose your message.

$headers = "From:" . $from;

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

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

This line is used for executing the function and checking whether it was successful.

echo "The email message was sent.";

A message will appear once the script is executed successfully.

echo "The email message was not sent.";

An alternative message will appear if the script is not executed successfully.

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 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 Composer installed. To install PHPMailer manually, you need to connect your hosting account via the 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. Once that is done, tap Enter. Remember that PuTTY will NOT display your password. Do not be confused if your password does not appear on the screen.
  6. Execute the following command:
    cd public_html
  1. Press Enter, then run this command:
    composer require phpmailer/phpmailer
  1. Wait for a moment until the installation process is finished. PHPMailer installation process.

Using PHPMailer with Hostinger SMTP

Once you have PHPMailer ready, you can use it to send PHP mails using Hostinger SMTP.

  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:Email SMPT details.

    NOTE: 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 and click on File Manager -> Go to File Manager.
  4. Press Add New. Name the file as testphpmailer.php and click Create.
  5. Double-click on the newly made testphpmailer.php file, then copy and paste the following:
    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.';
  1. Modify the above code accordingly. For example, you need to replace EMAIL_ACCOUNT_PASSWORD with your email password or with username, with a recipient email address, etc. Once that’s done, click Save & Close.
  2. Your PHPMailer is now ready to be used. Execute the script by entering in your browser.

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;

This line imports the PHPMailer class to the global namespace.

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

It’ll include various libraries that PHPMailer needs.


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

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

Defines what happens when the scripts are executed.

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

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

} else {

Specifies what happens if the script is executed.

echo 'The email message was sent!';

If the email is successfully sent, this message will appear.

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. This is done to avoid the end-user seeing the SMTP delivery report.

If you paid attention, you would notice that we’re doing something a little different compared to the first example — we are sending an HTML message rather than a plain piece of 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 change the color, style, image, or even include multimedia files that are usually obsolete in a plain text email.

PHPMailer Contact Form

You can use PHPMailer for more than just sending out a simple PHP mail. You can utilize it 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 with the previous scripts, you need to create a new file in the public_html folder. In this case, we named the file formscript.php. Edit the information inside the script accordingly. After that, you only need to run the script from your browser.

Here’s how the final result looks like:PHPMailer interactive contact form example. Once your customer submits a message, he will get a confirmation message, and the contents will arrive in the inbox of the email you entered here:

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

PRO TIP: If the PHPMailer contact form does not work, add the $mail->SMTPDebug = 2; line to see what causes the issue. Don’t forget to erase it or change the 2 to 0 once you’re 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 such plugins as WP Forms, Formidable Forms, or Gravity Forms.WP Forms frontpage.

Troubleshooting Common PHP Mail and PHPMailer Errors

Errors can occur from time to time while using PHP mail or PHPMailer. Here’s a list of the most common issues and ways how you can fix them.

Sender Address Rejected: Not Owned by the User

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

To fix it, check the email address you’ve used to send the message and make sure it corresponds to an existing email box. If it is pointing to a wrong inbox, change it accordingly. 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 enabled.
  • You’ve sent 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 are various reasons why PHP mail can turn up as spam. Here are some of the most common ones:

  • Misleading or spam-like subject. A few examples of that would be “test” or “testing”, hello“, “urgent” or anything similar. Make sure that you set a clear intent in your message subject.
  • You’re using an incorrect sender address that invokes the security measures to filter your email. This is done 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.
  • Your mailing list does not have an unsubscribe button. When many people 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 and invoke more trust from your readers.


Congratulations, you are now familiar with the PHP send email feature and how to 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. If you have any tips, tricks, or ideas to share, we are eager to hear them in the comments section below.

The author

Domantas G.

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.