How to Send Emails with PHP Mail() Function and PHP Mailer

How to Send Emails with PHP Mail() Function and PHP Mailer

You bought a domain and created your first email account. It’s time to finally send some emails, but you’re not entirely sure how to do just that.

If your website or web application is built on PHP, you can send emails via the PHP mail feature. This can be handy for creating custom-built mail forms and sending simple text-based email messages.

Usually, there are two options to send emails with PHP – the inbuild PHP mail() function or a mail-sending library such as PHPMailer.

In this tutorial, we will cover the differences between the PHP mail() function and PHPMailer and show you how to send emails with them.

Why and When Use the PHP Mail?

We recommend utilizing an external PHP mailing package if you want to send multiple emails more securely. The native PHP mail() function is not suited for large volumes of emails, as it opens and closes a Simple Mail Transfer Protocol (SMTP) socket connection with each email.

There are many PHP mail packages to choose from, including Pear Mail and Swift Mailer. In this article, we’ll use PHPMailer.

Before we begin, here’s a quick summary of the pros and cons of the PHP mail() function and PHPMailer:

mail() advantages:

  • Already pre-installed and ready to use, all you need is to have PHP
  • Backward-compatible so that a PHP version change won’t break the script
  • Easy to learn and use

mail() disadvantages:

  • Hard to set up with SMTP, which will trigger recipient SPAM filters
  • Not suitable for sending a large number of emails
  • Sending an email is a complicated process. Thus, using only a mail() function isn’t sufficient. Therefore, external libraries such as PHPMailer are recommended instead

PHPMailer advantages:

  • Introduces complex email structures, such as HTML documents and attachments
  • Supports SMTP, and authentication is integrated over SSL and TLS
  • Can be used to send high amounts of emails in a short period

PHPMailer disadvantages:

  • Requires installation
  • It does take a while to get used to and learn the logic

How to Use PHPMailer to Send Emails

PHPMailer is a popular mail-sending library that supports sending via the mail() function or through an SMTP server. It gives access to a set of functions for sending emails, simplifying the process of configuring PHP mail.

Installing PHPMailer

Installing PHPMailer is quite simple, especially if you have Composer installed. Our shared and cloud hosting plans include two versions of this software.

If you need an older Composer version, use the composer command. Otherwise, if you need a newer version or your PHP version is 8+, use the composer2 command.

To install PHPMailer manually, follow these steps:

  1. Connect to your account via an SSH client.
  2. From your hPanel dashboard, go to AdvancedSSH Access and take note of the SSH IP, port, username, and password under the SSH details.
  3. Open PuTTY and enter your SSH information in the Host Name (or IP address) and Port fields. Then, click Open.
  1. Once a command window appears, type in your SSH username and password and hit Enter. Remember that PuTTY will not display the password, so don’t be surprised if it doesn’t appear on the screen.
  2. Execute the following command to navigate to the public_html directory:
cd public_html
  1. Then, run the following command:
composer2 require phpmailer/phpmailer
  1. Wait a moment until the installation process is finished. Here’s what it should look like:
The terminal showcasing a successful PHPMailer  installation with Composer

Understanding PHPMailer Components

To understand how PHPMailer works, let’s review each script component above.

use PHPMailer\PHPMailer\PHPMailer;

The line above imports the PHPMailer class to the global namespace.

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

This line includes various libraries that PHPMailer needs.

$mail = new PHPMailer;

This creates a new PHPMailer object.

 $mail->isSMTP();

The code here tells PHPMailer class to use the custom SMTP configuration defined in the script instead of the local mail server.

$mail->SMTPDebug = 2;

The SMTPDebug command lets you detect if something goes wrong with the SMTP connection.

$mail->Host = 'smtp.hostinger.com';

This is where the SMTP server address should be specified.

$mail->Port = 587;

Set the SMTP port here.

$mail->SMTPAuth = true;

This line is used to turn on SMTP authentication.

$mail->Username = 'mymail@myawesomedomain.tld';

Specify your email address here.

$mail->Password = 'My$tr0ngPa55w0rd!;

Here, enter your email password.

$mail->setFrom('mymail@myawesomedomain.tld', 'Your Name');

This is where you insert the sender’s email address.

$mail->addReplyTo('mymail@myawesomedomain.tld', 'Your Name');

This line will let the recipient know which address they should reply to.

$mail->addAddress('recipient@domain.tld', 'Receiver Name');

Insert the recipient’s address here.

$mail->Subject = 'Checking if PHPMailer works';

Add the email’s subject line here.

$mail->msgHTML(file_get_contents('message.html'), __DIR__);

This line reads an HTML message body from an external file. The file_get_contents() function will load the content from message.html, a local file located in the public_html directory, and include it in the message.

$mail->Body = 'This is just a plain text message body';

This line contains the mail message body.

Pro Tip

Avoid “test” and “testing” in the email body or subject. Such terms can cause the recipients’ mail server to suspect you’re sending spam and block the email.

//$mail->addAttachment('attachment.txt');

If you want to include attachments, include the file names and remove the double slash from this statement.

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

This line defines what happens when the script is executed.

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

This will display an error message alongside an explanation if the script fails to send.

} else {

} else { extends the if statement and describes what happens if the previous condition is not met.

echo 'The email message was sent!';

Supposing that the email was sent successfully, this message will appear.

Pro Tip

The SMTPDebug = 2; line is only applicable when you test a script and want to see how it operates. Remember to change it to SMTPDebug = 0; when you are done with the test to prevent receivers from catching the SMTP protocol delivery report.

Using PHPMailer with Hostinger SMTP

After installing PHPMailer, you can finally begin sending PHP emails.

In this section, we’ll show you how to send email through the Hostinger SMTP server using PHPMailer:

Pro Tip

If you are using Titan Mail, use its SMTP server instead.

  1. Create an email account by accessing the hPanel, then going to Emails Email AccountsCreate email account.
  2. Fill in the new email address and set a password. Then, click Create. Remember this information as you will use it to send mail via PHPMailer.
  3. From the same page, go to Configuration SettingsManual Configuration and take note of the SMTP Port and Hostname.
  1. Access the hPanel dashboard and navigate to Files File Manager. Click on the public_html folder and select Add New to create a new file. Name the file phpmailer.php and click Create.
  2. Double-click on the phpmailer.php file, and copy and paste the code below. Modify it accordingly. Make sure to replace the mymail@myawesomedomain.tld and recipient@domain.tld with existing domains and My$tr0ngPa55w0rd! with your email account password.
<?php
   require 'vendor/autoload.php';
   use PHPMailer\PHPMailer\PHPMailer;
   $mail = new PHPMailer;
   $mail->isSMTP();
   $mail->SMTPDebug = 2;
   $mail->Host = 'smtp.hostinger.com';
   $mail->Port = 587;
   $mail->SMTPAuth = true;
   $mail->Username = 'mymail@myawesomedomain.tld';
   $mail->Password = 'My$tr0ngPa55w0rd!';
   $mail->setFrom('mymail@myawesomedomain.tld', 'Your Name');
   $mail->addReplyTo('mymail@myawesomedomain.tld', 'Your Name');
   $mail->addAddress('recipient@domain.tld', 'Receiver Name');
   $mail->Subject = 'Checking if PHPMailer works';
   $mail->msgHTML(file_get_contents('message.html'), __DIR__);
   $mail->Body = 'This is just a plain text message body';
   //$mail->addAttachment('attachment.txt');
   if (!$mail->send()) {
       echo 'Mailer Error: ' . $mail->ErrorInfo;
   } else {
       echo 'The email message was sent.';
   }
?>
  1. After editing the code, click Save & Close. To execute the script, enter yourdomain.tld/phpmailer.php in your web browser.

Creating a PHPMailer Contact Form

Other than using PHPMailer to send out simple PHP mail, users can also utilize it to create a contact form, allowing their audience to get in touch with them.

Similar to previous PHP scripts, creating a new PHP file in the public_html folder is essential before proceeding. Name it formscript.php.

Copy and paste the script below into the freshly created file and modify the information inside it accordingly:

<?php
use PHPMailer\PHPMailer\PHPMailer;
$msg = '';
if (array_key_exists('email', $_POST)) {
    require 'vendor/autoload.php';
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->Host = 'smtp.hostinger.com';
    $mail->Port = 587;
    $mail->SMTPDebug = 0;
    $mail->SMTPAuth = true;
    $mail->Username = 'mymail@myawesomedomain.tld';
    $mail->Password = 'My$tr0ngPa55w0rd!';
    $mail->setFrom('mymail@myawesomedomain.tld', 'Mr. Snuffles');
    $mail->addAddress('recipient@domain.tld', '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>Contact us</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>
    <label for="email">Email address: <input type="email" name="email" id="email"></label><br>
    <label for="message">Message: <textarea name="message" id="message" rows="8" cols="20"></textarea></label><br>
    <input type="submit" value="Send">
</form>
</body>
</html>

Pro Tip

Taking user input from ​​$_POST and using it unsanitized is not safe due to cross-site scripting (XSS) attacks. To avoid this, check out the best practices for PHP variable sanitization.

Save your changes, then run the script from your browser.

Here’s what the result will look like:

Browser showcasing the form script window

If a visitor submits a message via the form, they will get a confirmation message, and the form’s content will arrive in the inbox of the email address you entered here:

$mail->addAddress('recipient@domain.tld', 'Receiver Name');

Pro Tip

If the PHPMailer contact form does not work, change the $mail->SMTPDebug = 0; line to $mail->SMTPDebug = 2 to identify the causing issue. Don’t forget to remove the line or change the 2 to 0 afterwards.

To see other examples of how to use this mail-sending library, visit PHPMailer’s official repository on GitHub.

If you’re a WordPress user, you can instead use contact form plugins such as Formidable Forms, Gravity Forms, or WPForms to create contact forms.

How to Send Emails Using PHP Mail() Function

Another method to send emails directly from a PHP script is the built-in mail() function. To use the PHP send mail feature, users hosting their PHP application or site on a local server will need to configure a Sendmail program by changing the php.ini file in their PHP installation folder.

If you use a hosting server, Sendmail usually comes already pre-configured. However, you must ensure that your hosting provider allows you to manage the Sendmail service option manually.

Hostinger users can toggle this function by accessing the hPanel and navigating to EmailsMail Service Control.

Mail service control section on hPanel

By default, the Sendmail service is already enabled. Nevertheless, double-check to be sure.

Important! The PHP Mail function will be enabled by default if you use Titan Mail. Thus, it cannot be switched on or off in the hPanel.

Understanding PHP Mail Components

To help you understand the PHP mail() function, we’ll review the components of the PHP script we used in the previous section.

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

The first two lines above enable error reporting to inform you if the PHP script has failed to execute.

$from = "mymail@myawesomedomain.tld";

This line should contain the sender’s email address. Most hosting providers forbid adding random email addresses here, as it can be used for spoofing. Thus, it’s better to use one with your domain name to execute the script successfully.

$to = "recipient@domain.tld";

The recipient’s email address goes here. To deliver a message to multiple recipients, separate the email addresses with commas.

$subject = "Checking PHP mail";

Enter the subject line for the email here.

$message = "PHP mail works just fine";

Here, input the body of your email message.

$headers = "From:" . $from;

This line is commonly used to add additional headers, such as From, Reply-To, and Cc – these extra headers should be separated with a CRLF.

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

This line is used to execute the function and check whether it has run successfully.

echo "The email message was sent.";

The message above will appear when the script is executed successfully.

echo "The email message was not sent.";

Alternatively, this message will be displayed if it fails.

Keep in mind that although additional headers are optional, it’s essential to mention the From header when sending mail. Otherwise, you’ll receive a notification like this:

Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing.

For more information about the Sendmail function and its parameters, consult the official PHP documentation.

Creating a Test File for PHP Mail

After assuring that Sendmail is active, we must create a PHP mail script file and place it in the public_html directory.

Here’s how to do it:

  1. From hPanel, navigate to Files File Manager to access Hostinger’s File Manager.
  2. Double-click the public_html folder and select the New File icon at the top. Name this new file testmail.php, then hit Create.
  3. Double-click on testmail.php to edit it. You can use the basic PHP code below but change the parameters accordingly. We’ll describe the script components in more detail in the following subsection:
<?php
ini_set( 'display_errors', 1 );
error_reporting( E_ALL );
$from = "mymail@myawesomedomain.tld";
$to = "recipient@domain.tld";
$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.";
}
?>
  1. Click Save & Close once finished.
  2. Send the email by accessing yourdomain/testmail.php from your web browser. Remember to change “yourdomain” to the domain used when creating testmail.php.
A message showcasing how a PHP email appears in Gmail

Sending HTML Mails in PHP

PHP mail() function can also be used to send HTML-formatted emails. This format is highly customizable compared to plain text messages.

The process to send HTML mail is the same, but you need to include an HTML message and additional parameter headers this time.

Here is an example of a basic script to send an email with HTML formatting:

<?php
   ini_set( 'display_errors', 1 );
   error_reporting( E_ALL );
   $from = "mymail@myawesomedomain.tld";
   $to = "recipient@domain.tld";
   $subject = "Checking PHP mail";
   $message = "
   <html>
   <head>
       <title>This is a test HTML email</title>
   </head>
   <body>
       <p>Hi, it’s a test email. Please ignore.</p>
   </body>
   </html>
   ";
  // The content-type header must be set when sending HTML email
   $headers = "MIME-Version: 1.0" . "\r\n";
   $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
   $headers = "From:" . $from;
   if(mail($to,$subject,$message, $headers)) {
      echo "Message was sent.";
   } else {
      echo "Message was not sent.";
   }
?>

How to Troubleshoot Common PHP Mail and PHPMailer Errors

In the following section, we’ll review some of the most common issues that might occur when using the PHP mail() function or PHPMailer and how to fix them.

Sender Address Rejected: Not Owned by the User

This error means the server could not authenticate the sender using the provided details. To fix it, check the email address you’ve used to send the message and ensure it corresponds to an existing one.

Also, make sure your Sender Policy Framework (SPF) is enabled. If you use Hostinger, check your SPF record by going to the hPanel, and navigating to Emails Email Accounts DNS SettingsManage Email Delivery.

If the SPF record is enabled, it will be shown as Active.

Gmail Couldn’t Verify That Domain.TLD Sent This Message

If you see this warning when testing a PHP mail script, the cause might be one of the following:

  • There is no SPF record in the domain’s DNS Zone. If the record is missing, or you’re using external nameservers, add a new SPF TXT record manually via hPanel or cPanel.
  • You used invalid SMTP authentication details. Make sure to use an email address that exists and belongs to you.

Mail Goes to the Spam Folder

There are various reasons why PHP mail might trigger spam filters. Some of the most common examples include:

  • Misleading or spam-like subject. Examples include using terms such as “test” or “urgent.” Be sure to set a clear intent in the Subject line.
  • Incorrect sender address. This can invoke security measures to filter your email as prevention against email spoofing and scams.
  • Using spam trigger words. This includes phrases like “great offer” and “this is not spam.” Try changing the content of your message to see if this is the issue.
  • Your mailing list doesn’t have an unsubscribe link. Ensure to include an unsubscribe button to prevent this issue and build reader trust.

Conclusion

Sending emails is a fundamental marketing strategy for any business or website. The PHP mail() function is suitable for sending small volumes of simple text-based messages. Meanwhile, PHPMailer is a better and safer method for sending bulk emails or creating contact forms.

To send an email using the PHP mail feature, create a new PHP file in the public_html directory and input the mail() function. Then, execute the script using your web browser.

As for sending emails with PHPMailer, you’ll need to install a dedicated tool, create an email account for it, and include the values from your SMTP settings in PHPMailer’s script. Creating a new PHP file in the public_html folder is also essential.

In this tutorial, we went over the process of installing PHPMailer and creating a test script along with a functional form. We have also covered the process of sending emails with the PHP mail() function.

We hope you found this tutorial useful. If you have any further questions, leave them in the comments section.

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

Author
The Co-author

Ignas R.

Ignas takes great satisfaction in helping people tackle even the most complex technical issues. His current goal is to write easy-to-follow articles so that these issues will not happen at all. During his free time, Ignas likes to play video games and fix up things around his house.