A Complete Guide to Using the PHP mail() Function for Sending Emails
* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.
The ability to send emails directly from a website is essential for various reasons, from user registration confirmations to contact forms. PHP, as a popular server-side scripting language, offers a built-in mail()
function that allows developers to send emails easily. In this blog post, we’ll cover how to send a simple email using PHP’s mail()
function, provide a complete example of a web form that sends an email, and discuss how to upload this to a shared hosting platform like HostGator.
How to Send a Simple Email with the PHP mail() Function
PHP’s mail()
function is straightforward and provides an easy way to send email directly from your PHP script. Here’s the basic syntax of the function:
mail(to, subject, message, headers);
- to: The recipient’s email address.
- subject: The subject of the email.
- message: The body of the email.
- headers: Optional parameter for additional information such as
From
,CC
, andBCC
.
Simple Example:
Here’s a basic example of how to send an email using the mail()
function:
<?php
$to = "[email protected]"; // The recipient's email address
$subject = "Test Email from PHP"; // The email subject
$message = "Hello! This is a simple email sent using the PHP mail() function."; // The email body
$headers = "From: [email protected]"; // Optional headers, like "From"
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully.";
} else {
echo "Failed to send email.";
}
?>
In this example:
- We specify the recipient’s email, subject, message body, and headers.
- If the email is successfully sent, the function will return
true
and print a success message; otherwise, it will returnfalse
.
Complete Web Form Example to Send an Email
Now, let’s create a more practical example—a web form that allows users to input their name, email, and message, and then sends that information to a specified email address.
Step 1: Create the HTML Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
<form action="send_mail.php" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" name="email" required><br><br>
<label for="message">Message:</label>
<textarea name="message" required></textarea><br><br>
<input type="submit" value="Send Message">
</form>
</body>
</html>
In this form:
- Users can enter their name, email, and message.
- When the form is submitted, it sends the data to a PHP script (
send_mail.php
) via POST.
Step 2: Handle the Form Submission with PHP
Now, let’s create the send_mail.php
file to handle the form data and send the email.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = htmlspecialchars($_POST['name']); // Sanitize input
$email = htmlspecialchars($_POST['email']); // Sanitize input
$message = htmlspecialchars($_POST['message']); // Sanitize input
$to = "[email protected]"; // Your email address
$subject = "New message from $name via contact form";
$body = "You have received a new message from $name.\n\nEmail: $email\n\nMessage:\n$message";
$headers = "From: $email";
if (mail($to, $subject, $body, $headers)) {
echo "Message sent successfully!";
} else {
echo "Failed to send message.";
}
} else {
echo "Invalid request.";
}
?>
In this PHP script:
- We retrieve the form data using the
$_POST
superglobal. - The input is sanitized using
htmlspecialchars()
to prevent XSS (Cross-Site Scripting). - The
mail()
function sends the data to your email address with the user’s name, email, and message in the body.
How to Upload This to a Shared Hosting Platform Like HostGator
Once you have your PHP files ready (the form and the email handler), you’ll need to upload them to your shared hosting server. Here’s how to do this with HostGator (though the process is similar for other shared hosting providers):
Step 1: Access Your Hosting Account
- Log in to your HostGator cPanel.
- Navigate to the File Manager under the Files section.
Step 2: Upload the Files
- In the File Manager, navigate to your website’s directory, typically
/public_html/
. - Click Upload and select your HTML form and PHP files (e.g.,
index.html
andsend_mail.php
). - Once uploaded, your form will be live and accessible via your website.
Step 3: Test the Form
Open your browser and go to the URL of your contact form (e.g., https://yourwebsite.com/index.html
). Fill in the form and test sending an email to see if it works properly.
Common Issues on Shared Hosting
- Emails Not Sending: Some shared hosts block outgoing email functions to prevent spam. Check with HostGator’s support to ensure they allow PHP’s
mail()
function or ask for their recommended mail configuration. - SPF and DKIM Settings: Ensure your domain’s SPF and DKIM records are correctly configured to prevent your emails from being marked as spam.
Conclusion
The PHP mail()
function provides a simple and effective way to send emails directly from your website, especially for lightweight tasks like contact forms. In this post, we covered how to send a basic email, provided a full example of a contact form, and discussed how to deploy your form on a shared hosting platform like HostGator.
While the mail()
function is easy to implement, it does have its limitations when dealing with larger-scale applications. For more advanced use cases, libraries like PHPMailer or SwiftMailer might be worth considering. However, for most simple projects, mail()
gets the job done.
Resources:
By following the steps outlined in this blog post, you’ll be able to easily set up a contact form and send emails using PHP’s built-in mail function.