PHP mail() function can be used to send emails using PHP. It’s convenient if you want to implement contact form on your website. With PHP mail() emails can be sent using a simple PHP script. In this tutorial you will learn how to send emails using PHP and test PHP mail() function.
Table of Contents
What you’ll need
Before you begin this guide you’ll need the following:
- Access to your hosting account
- PHP mail() function enabled
Step 1 — Creating a new PHP file
First of all, you need to create a PHP file in your hosting account. Your PHP file should be accessible via domain name, therefore, it should be placed inside public_html folder. For file creation you can use File Manager or FTP client. Name your file testmail.php.
Step 2 — Editing the PHP file
Now place the following code inside testmail.php file:
ini_set( 'display_errors', 1 );
error_reporting( E_ALL );
$from = "testing@yourdomain";
$to = "recipientemailaddress";
$subject = "Checking PHP mail";
$message = "PHP mail works just fine";
$headers = "From:" . $from;
echo "The email message was sent.";
- First two lines enable errors reporting so you could see if the script has any errors and is failing to run.
- $from – Email sender address. Many hosting providers do not allow using random email address here so you need to enter
an email address created for your domain name in this field to successfully authorize and send the email.
- $to – The recipient email address. As you are sending this for testing purposes it can be your personal email.
- $subject – The subject of email.
- $message – The content of the email message.
- $headers – Every email has headers. They contain vital information such as From email address.
- mail($to,$subject,$message, $headers) – This is a PHP function which executes the email. You shouldn’t change anything on this line.
- echo “The email message was sent.” – PHP function echo will display a message on the screen once a script is executed successfully.
Step 3 — Running the script
If (as it was recommended) you have placed the PHP script in the public_html directory, you can now run the script by accessing yourdomainname/testmail.php. If you see the message
The email message was sent. on the browser it means the email was sent successfully and you can check for it in your inbox (do not forget to check the SPAM/JUNK folders).
If you get any errors you should check if you have entered all details correctly. If an error does not appear in the browser you can try checking the error_log file of your account. If you are not sure how to check this file check this tutorial on error logs.
Now you know how to send emails using PHP. Although this tutorial is for testing purposes, the same syntax can be used for developing a contact form on your website. However, if you need more advanced script for sending emails using PHP, check PHPMailer project. It has integrated SMTP support, comprehensive error_logs in 47 languages and many more useful features.