January 8, 2021
8min Read
Domantas G.
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 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.
If you’re already using Hostinger, you can enable or disable this function by accessing the hPanel. Click on Emails -> Mail Service Control.
By default, the Sendmail service is already enabled. Nonetheless, you should double-check it just to be sure.
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.
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; 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 = "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.
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.
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:
NOTE: PuTTY will NOT display your password. Do not be confused if your password does not appear on the screen.
cd public_html
composer require phpmailer/phpmailer
Once you have PHPMailer ready, you can use it to send PHP mails using Hostinger SMTP.
NOTE: You must remember the email account username, the account password, SMTP host, and SMTP port to send an email via PHPMailer.
<?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.'; } ?>
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.
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: 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.
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.
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.
If you see this warning when testing a PHP mail script, it could mean one of the following:
There are various reasons why a PHP mail can turn up as spam. Here are some of the most common ones:
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.
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,
Replied on June 15 2017
Hey, Can you provide more details? Do you get any errors?
June 18 2017
Thank you..it helped a lot......
February 23 2018
What is the SMTP Port number for Non-Secure?
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.
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;
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.
March 01 2019
Thanks Buddy, Worked great !
March 18 2019
Wow, thank you very much for the tutorials, they are very helpful.
May 10 2020
Thank You !!! Useful
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
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?
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! :)
August 09 2020
Whenever I put my ssh username and password the ssh command prompt automatically disappear .. how can i fix this
Replied on November 06 2020
Hey Suman. Make sure you are manually writing the SSH password. If you copy-paste it, it may not accept it and give you an empty response.
August 23 2020
Thank You, but the only thing is that I noticed that the mail was sent without and Avatar/Organization Picture and I don't know I can add that. Any Suggestion
Replied on November 06 2020
Hey there Joao. You can check this little thread here on how you can approach the task at hand.
September 09 2020
I have purchased domin and hosting but i didn't get it free 1 emailer so please tell....
Replied on November 11 2020
Hey Akshay! :) You can check here how to create your email in your new plan!
September 30 2020
for laravel smtp mail this works MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME=***@gmail.com MAIL_PASSWORD=****** MAIL_ENCRYPTION=tls but this is not working for me MAIL_DRIVER=smtp MAIL_HOST=smtp.hostinger.in MAIL_PORT=587 MAIL_USERNAME=mail@mywebsite.com MAIL_PASSWORD=********* MAIL_ENCRYPTION=tls MAIL_FROM_ADDRESS=mail@mywebsite.com MAIL_FROM_NAME="mail@mywebsite.com" error message "Expected response code 354 but got code "554", with message "554 5.5.1 Error: no valid recipients ↵" Any suggestion ????
Replied on November 18 2020
Hey there Sujith. Please drop a line to our Customer Success and we will help you out with it! :)
October 05 2020
hey I tested your PHP mail but it doesnt send an email though it confirms it was sent successfully. Can you please help me?
Replied on November 18 2020
Hey Joel. If you are sending something like "test" or "hey" email, it may get caught by the spam filter. Please try sending a normal email as test. If you still have an issue afterwards, just drop a line to our Customer Success team.
November 29 2020
Hey i tried this method to send a mail by making a request from a javascript page and the $_POST seems to be always empty. If i set everything as queryparams and do a get request it works but I want to do a post request and add the info in the body.
Replied on February 09 2021
Hi there! Did you receive any error messages with error display enabled or found anything in your error_log? If you won't be able to resolve it on your own, don't hesitate to contact our Customer Success team to help you troubleshoot!
November 30 2020
require(vendor/autoload.php): failed to open stream: No such file or directory
Replied on February 09 2021
Hi there! If you're getting this error, the chances are your composer isn't working correctly. Refer to article over here on how to install it ;)
December 23 2020
This page isn’t working mywebsite.com is currently unable to handle this request. HTTP ERROR 500
Replied on February 09 2021
Hi there! You'll find how to overcome error 500 over here - it will help you understand which line of code is an error and fix it :)
Domantas G.
Replied on June 14 2017
Hey, Can you elaborate?