How to Send Emails with PHP Mail() Function and PHP Mailer
If your website or web application is built on PHP, you can utilize the PHP mail feature to send emails. It can come in handy for creating custom-built mail forms and sending simple text-based email messages.
Download Website Launch Checklist
There are typically two ways of sending emails with PHP – using the inbuilt PHP mail() function or an email sending library such as PHPMailer.
In this tutorial, we’ll go over how to send emails using both methods and identify some common PHP mail issues, and how to fix them.
How to Send Emails Using PHP mail() Function
The first method to send emails directly from a PHP script is by using 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 is usually already configured. However, you need to make sure that your hosting provider allows you to manually manage the Sendmail service option.
Hostinger users can toggle this function by accessing the hPanel and navigating to Emails -> Mail Service Control.
By default, the Sendmail service is already enabled. Nevertheless, double-check it to be sure.
Creating a Test File for PHP Mail
After making sure that Sendmail is active, we’ll create a PHP mail script file and place it in the public_html directory.
Here’s how to do it:
- From hPanel, navigate to Files -> File Manager to access the Hostinger File Manager.
- Double click on the public_html folder and select the New File icon at the top bar. Name this new file testmail.php, then hit Create.
- Double click on testmail.php to edit it. You can use the basic PHP code below, but make sure to change its parameters accordingly. We’ll describe the script components in more detail in the next subsection.
<?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."; } ?>
- When you’re done editing, click Save & Close.
- Send the email by accessing YourDomain/testmail.php from the browser. Remember to change YourDomain to the domain used when creating testmail.php.
- The recipient will receive the message below:
Understanding PHP Mail Components
To help you understand the PHP mail() function, we’ll go over 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 tell you if the PHP script has failed to execute.
$from = "test@hostinger-tutorials.com";
This line should contain the sender’s email address. Most hosting providers forbid adding random email addresses here, as they can be used for spoofing. Thus, it’s better to use one with your domain name to execute the script successfully.
$to = "test@gmail.com";
The recipient’s email address goes here. If you want to deliver the message to multiple recipients, separate their 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 (\r\n
).
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. Alternatively, the message below will be displayed.
echo "The email message was not sent.";
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:
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.
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 = "test@hostinger-tutorials.com"; $to = "test@hostinger.com"; $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 Use PHPMailer to Send Emails
If you want to send multiple emails, it’s recommended to utilize an external PHP mailing package. The native PHP mail() function is not suited for larger 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.
PHPMailer is a popular mail sending library that supports mail 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.
How to Install PHPMailer
Installing PHPMailer is quite simple, especially if you have Composer installed – many shared hosting plans include this tool.
Important! We recommend using Composer 2 if you are running PHP 8.
To install PHPMailer manually, connect your hosting account via the SSH terminal by following these steps:
- Download and install the PuTTY SSH client.
- From your hPanel dashboard, go to Advanced -> SSH Access and take note of the SSH IP, port, username, and password under the SSH Access information.
- Open PuTTY and enter your SSH information in the Host Name (or IP address) and Port fields. Then, click Open.
- 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 confused if it doesn’t appear on the screen.
- Execute the
cd public_html
command and press Enter. - Then, run the
composer require phpmailer/phpmailer
command and hit Enter.
Important! If you are using Composer 2, run the composer2 require phpmailer/phpmailer
command instead
- Wait for a moment until the installation process is finished.
Using PHPMailer with Hostinger SMTP
After installing PHPMailer, you can start using it to send PHP emails.
In this section, we’ll show you how to send email through the Hostinger SMTP server using PHPMailer:
- Create an email account by accessing the hPanel, then going to Emails -> Email Accounts -> Create New Email Account.
- Fill in the new email address and set a password. Then, click Create. Make sure to remember this information as you’re going to use it to send mail via PHPMailer.
- From the same page, go to Configuration Settings -> Manual Configuration and take note of the SMTP Host and Port.
- 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 testphpmailer.php and click Create.
- Double-click on the testphpmailer.php file, then copy and paste the code below and modify it accordingly. Make sure to replace the test@hostinger-tutorials.com with your Hostinger email address and EMAIL_ACCOUNT_PASSWORD with the 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 = 'test@hostinger-tutorials.com'; $mail->Password = 'EMAIL_ACCOUNT_PASSWORD'; $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.'; } ?>
- After editing the code, click Save & Close. To execute the script, enter YourDomain.com/testphpmailer.php in the browser.
Understanding PHPMailer Components
To understand how PHPMailer works, let’s take a look at each component of the script 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 is used to tell the 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 see 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 = 'test@hostinger-tutorials.com';
Specify your email address here.
$mail->Password = 'EMAIL_ACCOUNT_PASSWORD';
Here, enter your email password.
$mail->setFrom('test@hostinger-tutorials.com', 'Your Name');
This is where you should insert the sender’s email address.
$mail->addReplyTo('test@hostinger-tutorials.com', 'Your Name');
This line will let the recipient know which address they should reply to.
$mail->addAddress('example@email.com', 'Receiver Name');
Insert the recipient’s address here.
$mail->Subject = 'Testing PHPMailer';
Add the email’s subject line here.
$mail->msgHTML(file_get_contents('message.html'), __DIR__);
This line is used to read an HTML message body from an external file. The file_get_contents()
function here 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 a plain text message body';
This line contains the mail message body.
//$mail->addAttachment('test.txt');
If you want to include attachments, include the file names and remove the double slashes from this statement.
if (!$mail->send()) {
This line defines what happens when the script is executed.
echo 'Mailer Error: ' . $mail->ErrorInfo;
It’ll display an error message with an explanation if the script fails to send.
} else {
Else
extends the if
statement and describes what happens if the previous condition was not met.
echo 'The email message was sent!';
If the email was sent successfully, 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. Remember to change it to SMTPDebug = 0; if you are done with the test, preventing the receivers from seeing the SMTP delivery report.
Creating a PHPMailer Contact Form
Aside from 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.
Like with the previous PHP scripts, creating a new PHP file in the public_html folder is essential before proceeding. Name it formscript.php.
Then, copy and paste the script below into the newly created file and modify the information inside it accordingly:
<?php require 'vendor/autoload.php'; use PHPMailer\PHPMailer\PHPMailer; $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>
Pro Tip
Taking user input from $_POST and using it unsanitized can be insecure because of XSS (cross-site scripting) 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:
If a visitor submits a message through 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('example@gmail.com', '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.
To see other examples of using this mail sending library, visit PHPMailer’s official GitHub repository.
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 Troubleshoot Common PHP Mail and PHPMailer Errors
In the following sections, we’ll go over 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 that the server was unable to authenticate the sender 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 one. If it’s pointing to a wrong address, change it.
Also, make sure your Sender Policy Framework (SPF) is enabled. If you use Hostinger, check your SPF record by going to the hPanel, and navigate to Emails -> Email Accounts ->DNS Settings -> Manage Email Delivery. If the SPF record is enabled, it will be shown as Active:
Gmail Couldn’t Verify That YourDomain.com Sent This Message
If you see this warning when testing a PHP mail script, the reason 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 on your 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 ones are:
- Misleading or spam-like subject. A couple of examples include “test” or “urgent.” Be sure to set a clear intent in the subject.
- Incorrect sender address. This can invoke the security measures to filter your email as a 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 problem.
- The mailing list doesn’t have an unsubscribe button. Make sure to include an unsubscribe button to prevent this issue and build reader trust.
Conclusion
The PHP mail() function is suitable for sending small volumes of simple text-based messages. Meanwhile, PHPMailer is a better method for sending mass emails or creating a contact form.
To recap, in order 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 browser.
As for sending emails with PHPMailer, you’ll need to install the tool, create an email account for it, and include the values from your SMTP settings in PHPMailer’s script. It’s also essential to create a new PHP file in the public_html folder.
This tutorial contains basic syntax examples which can be further used for developing a contact form or other extensions for your website.
If you have any tips, tricks, or ideas, feel free to share them in the comments section below.
Comments
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,
June 14 2017
Hey, Can you elaborate?
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?
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;
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?
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
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
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....
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 ????
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?
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.
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
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
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 :)
September 07 2021
I am trying to send mails through PHP Mail component through contact form of website. But HTTP Error 500 responds every time. Is web server not suitable for PHP Mail service ?
September 20 2021
Hi there, HTTP 500 error suggests that there's likely an issue with the code of the file you're trying to execute. I'd suggest to look through your code again with a PHP error log or error display :)
September 29 2021
Hi there! I have tested sending mails by following your phpmailer tutorial and it worked. Great tutorial. Thanks!
September 29 2021
Happy it worked out!
October 04 2021
Sending the testmail through my browser doesn't work. When I type mydomain.com/testmai.php in a chrome address bar.l It takes me to the website 404 page not found.
October 05 2021
Hi Terry, please make sure to double-check your URL - it looks like you might be missing an L at the end of your URL - mydomain.com/testmail.php If anything, double-check the directory in which you placed your testmail file and ensure it's correct. Good luck!
January 15 2022
My site php mail() function is not working, please what should I do?
January 18 2022
Hi Eddy, first thing I would check what error you're receiving when you try to run it. If it suggests a code error, I would check to make sure the code and values inside of your phpmailer file are correct. If it says that the email is sent, but you don't receive it, there might be an issue with your sendmail service, emails going to spam, lack of SPF or DKIM records. If that's case, I'd suggest to check with your host :)
March 19 2022
Nice tutorial. Please how do I go about creating and auto welcome email for anyone who registers in my website
March 22 2022
Hi there :) It would depend on what CMS/framework you're using for your website, but generally, what you're looking for is the script, which registers new users to include a trigger to send a PHP mail. Then simply create the PHP mail file with your desired content! Let me know how it goes for you :)
April 23 2022
if i were to use an SMTP Relay service (e.g., Mail Jet, SendGrid, MailGun) other than hostinger.com's SMPT. how would i go about updating the DNS mx record to work with those SMTP Relay services?
April 25 2022
Hi William! You'd need to (1) get the required MX and other necessary DNS records from the new service provider; then (2) change them on your Hostinger DNS zone like this. If you run into any issues, feel free to check in with our Customer Success team!
June 02 2022
thank you, it helpful
June 03 2022
Hi, please am trying to access my test.php file from an external html using ajax, but it's not working, used allow access origin in htaccess but still no good news
June 07 2022
Hi there! I'd suggest to start by looking at the permissions of your test.php file - it could be that they're not set well for what you're intending to do 😊