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

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 G Suite, 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 manually manage the Sendmail service option.

Having trouble sending mails? PHP mail() is enabled by default on Hostinger.

Get a Discount for Web Hosting

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 just 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:

<?php
    ini_set( 'display_errors', 1 );
    error_reporting( E_ALL );
    $from = "test@hostinger-tutorials.com";
    $to = "test@hostinger.com";
    $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 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 = "test@hostinger-tutorials.com";

This line should contain the email address of the sender. 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 = "test@gmail.com";

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.

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

This line is used for executing the function.

echo "The email message was sent.";

A message that will appear once the script is 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 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 Composer installed. If you’re using Hostinger, you do not need to worry about this since it already comes pre-installed with all our hosting plans.

Nonetheless, if you need to install PHPMailer manually, 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. Once that is done, tap Enter.
  6. NOTE: PuTTY will NOT display your password. Do not be confused if your password does not appear on the screen.

  7. 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:
<?php
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'test@hostinger-tutorials.com';
$mail->Password = 'YOUR PASSWORD HERE';
$mail->setFrom('test@hostinger-tutorials.com', 'Your Name');
$mail->addReplyTo('test@hostinger-tutorials.com', 'Your Name');
$mail->addAddress('example@email.com', 'Receiver Name');
$mail->Subject = 'Testing PHPMailer';
$mail->msgHTML(file_get_contents('message.html'), __DIR__);
$mail->Body = 'This is a plain text message body';
//$mail->addAttachment('test.txt');
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 test@hostinger-tutorials.com to your username, example@gmail.com with your 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 YourDomain.com/testphpmailer.php 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.

$mail->

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 will 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. 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:

<?php
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->Host = 'smtp.hostinger.com';
    $mail->Port = 587;
    $mail->SMTPAuth = true;
    $mail->Username = 'test@hostinger-tutorials.com';
    $mail->Password = 'EMAIL_ACCOUNT_PASSWORD';
    $mail->setFrom('test@hostinger-tutorials.com', 'Mr. Drago');
    $mail->addAddress('example@gmail.com', 'Receiver Name');
    if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
        $mail->Subject = 'PHPMailer contact form';
        $mail->isHTML(false);
        $mail->Body = <<<EOT
Email: {$_POST['email']}
Name: {$_POST['name']}
Message: {$_POST['message']}
EOT;
        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">
<head>
    <meta charset="UTF-8">
    <title>Contact form</title>
</head>
<body>
<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">
</form>
</body>
</html>

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('example@gmail.com', 'Receiver Name');

PRO TIP: In case 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 YourDomain.com 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 can find the steps on how to add one here.
  • 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 a 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 there are a lot 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 and invoke more trust from your readers.

Conclusion

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

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

Author

Anderson Carvalho Reply

June 13 2017

Cool article, But I have a problem with this part: 'smtp', 'host' => 'smtp.mailgun.org', 'port' => 587, 'from' => array('address' => 'something@gmail.com', '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,

    Author

    Domantas G.

    Replied on June 14 2017

    Hey, Can you elaborate?

    Author

    Domantas G.

    Replied on June 15 2017

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

Author

Ashwin Reply

June 18 2017

Thank you..it helped a lot......

Author

Niroj Reply

February 23 2018

What is the SMTP Port number for Non-Secure?

    Author

    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.

Author

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;

    Author

    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.

Author

vipul Bhatt Reply

March 01 2019

Thanks Buddy, Worked great !

Author

Lucas Reply

March 18 2019

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

Author

Sedric Tighankpa Reply

May 10 2020

Thank You !!! Useful

Author

Bala Reply

June 08 2020

Just adding that, for people without SSH access and unable to install composer, they can still use PhpMailer. Please refer the below link https://stackoverflow.com/questions/48128618/how-to-use-phpmailer-without-composer

Author

Jorge Centeno Reply

July 04 2020

I have been trying to test this code and realized that whenever I add the following lines I get error 500 use PHPMailer\PHPMailer\PHPMailer; require 'vendor/autoload.php'; Is this outdated?

    Author

    Tomislav T.

    Replied on July 07 2020

    Hey there Jorge! :) To use that script you will need composer to be installed and enabled first. Please follow the guide here. If you still struggle with it, you can always message our support team! I am sure they will be happy to help! :)

Leave a reply

Comment*

Name*

Email*

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

Close