How to Send Emails Using PHP mail

How to send emails using PHP mail and PHPMailer

In this tutorial, we will learn about PHP mail and how to use it. We’ll also show you how to configure and use PHPMailer — a popular mail sending library.

Overall, email is an integral part of any project or business. Nowadays, being quick and responsive is a huge value, especially when it comes to answering your customers. In a lot of cases, responsiveness and well-planned communication are the deciding factors that users take into consideration when making purchases.

While there are numerous ways to deliver mails, we’ll be looking into PHP mail specifically. At the very core, you can send emails via PHP in two ways:

  • by using PHP’s inbuilt mail() function;
  • by using a third-party library such as PHPMailer with SMTP.

Let’s see how each one works and how we can use it to deliver emails!

What you’ll need

Before you begin this guide you’ll need the following:

Method 1 — Using PHP mail() function

The mail() function in PHP allows sending email using a local sendmail program. Whenever you call the mail() function, it invokes a local sendmail program, usually configured by the system administrator. If your web hosting is at Hostinger, you can enable/disable this functionality in Emails -> Mail Service Control section.

Mail Service Control section in Hostinger panelThe sendmail service is enabled by default. But in case it’s not, you can do it in just a few clicks.

Managing sendmail, POP3/IMAP, and SMTP services

Step 1 — Creating a test file for PHP mail

First of all, we will need to create a file for the PHP mail script. We’ll place it in the public_html directory so that it could be easily accessed through the domain name. You may use the File Manager or an FTP client for this task. Let’s name the file testmail.php.

PHP mail test file example

Step 2 — Understanding PHP mail

Let’s introduce ourselves with the components of a basic PHP mail script:

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

The first two lines enable error reporting. This will let help in case the script fails to execute. The remaining ingredients are:

$from Email sender address. Most hosting providers do not allow using random email addresses here, as it can be used for spoofing. You should enter an email address created for your domain name to successfully execute the PHP mail.
$to The recipient email address. As we are sending this for testing purposes it can be a personal email.
$subject The subject of the email message.
$message This section is for the message content.
$headers  Headers specify vital information, such as the sender address, the reply-to location and more.
mail ($to,$subject,$message,$headers)  This is the function that executes PHP mail.
echo “The PHP mail was went successfully.” The following message will appear once the script executes.

For more information about sendmail and its components, you can refer to the official PHP documentation.

Step 3 — Running the PHP mail script

If you placed your PHP script in the public_html directory, you can it run by accessing You should see the following message:

PHP mail sent successfullyHere’s an example of the received PHP mail using the above code:

PHP mail arrival exampleCongratulations! You now understand the basic syntax of PHP mail and can use it to send messages.

Method 2 — Using PHPMailer

PHPMailer is a popular mail sending library for PHP. It supports mail sending via mail() function or SMTP. In short, PHPMailer is an effective method to send emails in a PHP based environment.

Step 1 — Gathering details for PHPMailer

To use PHPMailer with Hostinger SMTP, you will first need to create an email account. You can do this at Email Account section in the web hosting panel.

Creating a new email accountOnce you’re done, grab your SMTP details located in the same section:

SMTP, IMAP, and POP3 details on Hostinger

You should have four ingredients by now, which are:

  1. Email account username
  2. Email account password
  3. SMTP host
  4. SMTP port

Step 2 — Installing PHPMailer

Since we have all the required details, we can begin the PHPMailer setup. One easy way to do it is by using Composer. It’s pre-installed on our shared hosting plans, so you’ll only need to connect via SSH and execute the following command:

cd public_html

And then run:

composer require phpmailer/phpmailer

Wait a few moments for the installation to finish and PHPMailer will appear in a newly created vendor directory.

Step 3 — Understanding PHPMailer

To understand PHPMailer and how it works let’s investigate an example that uses SMTP for delivery.

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 = 'EMAIL_ACCOUNT_PASSWORD';
$mail->setFrom('', 'Your Name');
$mail->addReplyTo('', 'Your Name');
$mail->addAddress('', 'Receiver Name');
$mail->Subject = 'PHPMailer SMTP message';
$mail->msgHTML(file_get_contents('message.html'), __DIR__);
$mail->AltBody = 'This is a plain text message body';
if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message sent!';

Let’s see what each component does:

use PHPMailer\PHPMailer\PHPMailer; This line imports the PHPMailer class to the global namespace.
require ‘../vendor/autoload.php’; Includes various libraries that PHPMailer needs.
$mail-> All these variables contain vital information, such as server details, headers, message, attachments and more. In short, they ensure that the sender is legit with SMTP authentication.
if (!$mail->send()) { Defines what happens when the scripts execute.
echo ‘Mailer Error: ‘ . $mail->ErrorInfo; If the script fails to send, you will see what went wrong.
else Defines what happens if the script does execute.
echo ‘Message sent!’;  This message will appear to the user if everything works.

Pro Tip: The line SMTPDebug = 2; is useful when testing the script and seeing how it works.

Set it to SMTPDebug = 0; in the final version to avoid the end user from seeing the SMTP delivery report.

If you checked the whole code, you will notice that we are doing something a little different than in the first example. We are sending an HTML message. Its content will be taken from the message.html file located in the same directory. This lets you format the text and gives greater functionality compared to plain text messages.

Step 4 — Running the PHPMailer script

Lets create a testphpmailer.php file and fill in all the fields with the SMTP details we retrieved earlier. Execute the script by entering in the browser and you will see a similar message:

PHPMailer test SMTP message successHere’s an example of the received email message:

Receiver view of PHPMailer SMTP messageNotice how the text is formatted this time, as we used HTML instead of plain-text. Furthermore, we were able to add a file attachment.

Step 5 — PHPMailer contact form example

You can use PHPMailer for much more than just sending out simple messages. One way you can utilize it is to create a contact form where your visitors or users can get in touch with you. Here’s a basic example of such 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 = 'Invalid email address, message ignored.';
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Contact form</title>
<h1>Let's get in touch!</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">

And the end result is:

Basic contact form created with PHPMailerOnce the user submit his message, he will get a confirmation and the contents will arrive at the e-mail box entered in the addAddress field.

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 remove it or set to zero once done!

PHPMailer offers extra 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.

Troubleshooting common PHP mail and PHPMailer errors

PHPMailer is quite an easy tool to master. But errors can occur from time to time. Let’s see the list of most common errors while sending PHP mail and how we can fix them.

Sender address rejected: not owned by the user

The sender address rejected: now owned by user error means that the server was unable to authenticate using the provided details. To fix it, check the from headers and make sure they correspond to an existing e-mail box. If not, make sure to create or change it and the script will start executing. Lastly, make sure that your SPF record is enabled.

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 may find the steps on how to create it here.
  • The from header uses an e-mail address that does not exist or is not owned by you. Make sure to use valid SMTP authentication details.

Mail goes to the spam folder

There can be various reasons why a message can turn up in the spam box. Let’s see a few common ones:

  • Misleading or spammy subject. A few examples would be “Test“; “Hello“; “Testing“; “Urgent” or similar. Make sure that you set a clear intent in your message subject.
  • Incorrect from headers often cause this. It’s a security measure to prevent e-mail spoofing and scams.
  • You used spam trigger words. This category would include phrases as “great offer“; “click here“; “special promotion“; “this is not spam” and similar. Try changing up your message content to see if that’s the case.
  • Your mailing list does not have an unsubscribe button. If enough people report your mails as spammy, then this is bound to happen. Having an unsubscribe button is a great way to avoid this.


Congratulations! You are now familiar with PHP mail and can use PHPMailer to send e-mails 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 official PHPMailer project.

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

About the author

Gediminas B.

Gediminas was a passionate content writer and SEO geek at Hostinger. He started his journey at customer support and aims to use his gathered knowledge to create the most epic content the world has ever seen. From WordPress to server management, there's no topic he can't cover! He also likes cats.


Click here to post a comment

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

  • Cool article, But I have a problem with this part:

    ‘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,

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

  • 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;

    • 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.

Get Exclusive Content

Join thousands of webmasters who get our free newsletter with tips on how to drive more traffic and revenue to their websites!

Please wait...

Thank you for sign up!

More in Email
How to Setup Email on Android