Sending Email with PHP Using the mail() Function and Creating a Contact Us Form

Sending Email with PHP Using the mail() Function and Creating a Contact Us Form

All online business managers are aware that without frequent use of email, they will not be able to take control of their operations. Simply put, as a webmaster, you must always look for a reliable way to communicate with your users, and establishing this communication requires the use of email.

But what should you do to send email with PHP? You may already be familiar with various email platforms or even use them, but you should know that you can easily implement your own dedicated email sending system using PHP’s built-in capabilities or more modern libraries such as PHPMailer.

Today, we will teach you how to create an email sending protocol and a contact form using the mail() function as well as the professional PHPMailer library. If you are looking to easily send emails to your website customers or design a contact form that never sends emails to the spam folder, stay with us in this article.

Before anything else, let’s clarify an important fact. The mail() function in PHP is one of the oldest methods of sending email, and on many modern servers, due to security and anti-spam reasons, it does not function properly or emails sent with it go directly to spam. For this reason, in this article, we will first learn the mail() function so that you become familiar with the basic logic, but then we will move on to the main and professional method—using the PHPMailer library with SMTP—which, in 2026, is considered the gold standard for sending email in PHP.

Sending Email with the mail() Function in PHP

Using the mail() function is very simple from a coding perspective, but its success entirely depends on your server configuration. If you are on shared hosting, Sendmail or Postfix is usually already enabled. If you are working on your own VPS, you must install and configure this service yourself.

Enabling the Sendmail Service (or Any Other MTA)

Before moving on to coding, you need to make sure that the email sending service is active on your server. On cPanel hosting, there is usually nothing special you need to do. However, if you are on a Linux VPS, you can check the status with the following commands:

systemctl status sendmail

Or if you are using Postfix:

systemctl status postfix

If the service is not active, install and enable it with the following commands (on Ubuntu/Debian):

sudo apt install sendmail
sudo systemctl enable sendmail
sudo systemctl start sendmail

On shared hosting with control panels like cPanel or DirectAdmin, you can check the status under Email Services or Mail Service Control. By default, these services are enabled, but if your emails are not being sent, the first step is to check this section.

Creating a Test File for PHP Mail

Now let’s create a simple file to test the mail() function. Go to your hosting file manager (or connect via FTP) and create a new file in the public_html folder named, for example, testmail.php. Place the following code inside it:

<?php
// Enable error display for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Email settings
$from = "noreply@yourdomain.com";  // Make sure to use your own domain
$to = "yourpersonalemail@gmail.com";
$subject = "Testing the mail function in PHP";
$message = "This is a test email sent using the mail() function.";
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: " . $from . "\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

// Send email
if(mail($to, $subject, $message, $headers)) {
    echo "Email was sent successfully.";
} else {
    echo "Error sending email. Please check the server logs.";
}
?>

Now open this file in your browser at https://yourdomain.com/testmail.php. If you see a success message, the mail() function is working. If you see an error or do not receive the email, don’t worry—we will address this in the troubleshooting section.

Understanding the Components of the mail() Function

Let’s review the parameters of the mail() function line by line:

ini_set(‘display_errors’, 1) and error_reporting(E_ALL): These two lines ensure that if there is any error in your script, it will be displayed directly in the browser. In a production (live) environment, it is better to remove or disable these lines.

$from: The sender’s email address. Many hosting providers only allow you to use email addresses that match your domain. For example, if your website is yourdomain.com, you cannot use test@gmail.com as the sender.

$to: The recipient’s email address. For testing, you can enter your personal email.

$subject: The subject of the email. Try to make it clear and relevant. Avoid overusing words like “test” or “hello” as they may increase the likelihood of being marked as spam.

$message: The main body of the email. You can also use HTML, but in that case, you must add the header Content-Type: text/html.

$headers: The email headers. This is the most important part, including the sender, reply-to address, and content type. Make sure each header is separated by \r\n.

Disadvantages of Using mail() in 2026

To be honest, today almost no professional developer uses the mail() function for real-world projects. Why?

  • It lacks authentication, so emails easily end up in spam folders.
  • It depends on server configuration and may behave differently across hosting environments.
  • It has limited support for modern features like TLS, rich HTML formatting, and attachments.
  • It is completely unsuitable for services like Gmail and Outlook that require two-factor authentication and OAuth.

For this reason, from this point forward, we will focus on the standard and professional method: using PHPMailer with SMTP.

Sending Professional Email with PHPMailer and SMTP

PHPMailer is an open-source and very powerful library that turns sending email with PHP into an enjoyable experience. This library supports SMTP with authentication, TLS/SSL, HTML emails, attachments, and even bulk emails.

Installing PHPMailer

There are two methods for installation. The first and recommended method is using Composer. If Composer is installed on your server, simply create a composer.json file in your project root or run the following command directly:

composer require phpmailer/phpmailer

The second method is to manually download the library from the GitHub repository (github.com/PHPMailer/PHPMailer) and place it in your project folder. However, I strongly recommend the Composer method because it makes updating and dependency management much easier.

Sending a Simple Email with PHPMailer and Gmail SMTP

Suppose you want to use Google’s SMTP service to send email. First, create an App Password in your Google account (if two-factor authentication is enabled). Then place the following code in a file such as sendmail_advanced.php:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // SMTP server settings
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your-email@gmail.com';
    $mail->Password   = 'your-app-password'; // App password, not your regular password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    // Sender and recipient settings
    $mail->setFrom('your-email@gmail.com', 'Your Website Name');
    $mail->addAddress('receiver@example.com', 'Recipient Name');

    // Email content
    $mail->isHTML(true);
    $mail->Subject = 'Testing Email Sending with PHPMailer';
    $mail->Body    = 'This email was sent <strong>successfully</strong> using PHPMailer.';
    $mail->AltBody = 'This is the plain text version for non-HTML email clients.';

    $mail->send();
    echo 'Email sent successfully.';
} catch (Exception $e) {
    echo "Error sending email: {$mail->ErrorInfo}";
}
?>

If you are using another service such as Yahoo, Office 365, or your own hosting provider, you only need to change the Host, Port, Username, Password, and SMTPSecure settings according to that service.

Adding Attachments to Email

One of PHPMailer’s strengths is its excellent support for file attachments. Simply use the addAttachment method before calling $mail->send():

$mail->addAttachment('/path/to/file.pdf', 'display_name.pdf');

You can also use the path to an online file. For example, if the file is located on your server, provide its full path.

Building a Complete and Secure Contact Form with PHP and PHPMailer

Now that we are familiar with the basics, let’s build a professional contact form where users can enter their name, email, and message, and have the email sent to the site administrator. This code includes basic security measures (such as preventing email injection and XSS) and server-side validation.

Create a new file named contact.php in your public_html folder and place the following code inside it:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';

$msg = '';
$msgClass = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Receive and sanitize data
    $name = htmlspecialchars(strip_tags(trim($_POST['name'] ?? '')));
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $message = htmlspecialchars(strip_tags(trim($_POST['message'] ?? '')));

    // Validation
    if (empty($name) || empty($email) || empty($message)) {
        $msg = 'Please fill in all fields.';
        $msgClass = 'error';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $msg = 'Invalid email address.';
        $msgClass = 'error';
    } else {
        // Send email using PHPMailer
        $mail = new PHPMailer(true);
        try {
            // SMTP settings (change according to your service)
            $mail->isSMTP();
            $mail->Host       = 'smtp.yourhost.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'contact@yourdomain.com';
            $mail->Password   = 'your-email-password';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = 587;

            // Sender and recipient
            $mail->setFrom('contact@yourdomain.com', 'Website Contact Form');
            $mail->addAddress('admin@yourdomain.com', 'Site Administrator');
            $mail->addReplyTo($email, $name);

            // Email content
            $mail->isHTML(true);
            $mail->Subject = "New message from {$name}";
            $mail->Body    = "
                <h3>New message from contact form</h3>
                <p><strong>Name:</strong> {$name}</p>
                <p><strong>Email:</strong> {$email}</p>
                <p><strong>Message:</strong><br>{$message}</p>
            ";
            $mail->AltBody = "Name: {$name}\nEmail: {$email}\nMessage:\n{$message}";

            $mail->send();
            $msg = 'Your message has been sent successfully. We will contact you soon.';
            $msgClass = 'success';

            // Clear form (optional)
            $name = $email = $message = '';
        } catch (Exception $e) {
            $msg = "Message sending failed: {$mail->ErrorInfo}";
            $msgClass = 'error';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Us Form</title>
    <style>
        body { font-family: Tahoma, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; background: #f4f4f4; }
        .contact-form { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, textarea { width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; font-family: inherit; }
        button { background: #0073aa; color: #fff; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-size: 16px; }
        button:hover { background: #005a87; }
        .msg { padding: 10px; margin-bottom: 20px; border-radius: 4px; }
        .msg.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .msg.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>
    <div class="contact-form">
        <h2>Contact Us</h2>
        <?php if(!empty($msg)): ?>
            <div class="msg <?php echo $msgClass; ?>"><?php echo $msg; ?></div>
        <?php endif; ?>
        <form method="POST" action="">
            <label for="name">Full Name</label>
            <input type="text" name="name" id="name" value="<?php echo isset($name) ? htmlspecialchars($name) : ''; ?>" required>

            <label for="email">Email Address</label>
            <input type="email" name="email" id="email" value="<?php echo isset($email) ? htmlspecialchars($email) : ''; ?>" required>

            <label for="message">Your Message</label>
            <textarea name="message" id="message" rows="6" required><?php echo isset($message) ? htmlspecialchars($message) : ''; ?></textarea>

            <button type="submit">Send Message</button>
        </form>
    </div>
</body>
</html>

This code follows all basic security practices: preventing XSS with htmlspecialchars, validating email addresses, and preventing additional header injection. It also provides a good user experience by displaying success or error messages.

Creating a Contact Form in WordPress (Without Coding)

If you use WordPress and don’t want to write code, the best option is to use professional plugins. Plugins such as WPForms (the free version has limitations but is powerful), Contact Form 7 (free and popular), and Quform (paid but professional) are excellent choices.

I personally recommend WPForms to WordPress users because it has a simple user interface and integrates well with SMTP. Just remember that to prevent your contact form emails from going to spam, be sure to install an SMTP plugin such as WP Mail SMTP and configure email sending through SMTP (for example, via Google or your hosting provider).

Fixing Common Errors When Sending Email with PHP

In this section, we will review the most common errors you may encounter when working with email in PHP:

“Sender Address Rejected” Error

This error means that the recipient’s mail server does not accept your sender address. Possible reasons: the sender address does not belong to your domain, or the SPF record for your domain is not properly configured. To fix this, always use a valid email address with your own domain and add an SPF record to your domain’s DNS: v=spf1 include:_spf.google.com ~all (if you are using Google).

Emails Go to the Spam Folder

This problem is very common. Solutions:

  • Never use spam-like subject lines such as “You’ve Won,” “Special Offer,” or “Test.”
  • Always include an Unsubscribe link in bulk emails.
  • Use DKIM, SPF, and DMARC for your domain.
  • Maintain a proper text-to-image ratio (more text than images).
  • Check your email using tools like Mail-tester.com before sending bulk emails.

“Gmail Couldn’t Verify That YourDomain.com Sent This Message” Error

This error indicates that Google cannot verify that the email was actually sent from your domain. Solution: properly configure your SPF, DKIM, and DMARC records. Also, avoid sending emails from IP addresses with poor reputation. The best approach is to use SMTP services from reputable providers such as SendGrid, Mailgun, or Google’s own SMTP.

“Connection Refused” or “Unable to Connect to SMTP” Error

This error means that PHP cannot connect to the SMTP server. It is usually caused by firewall restrictions or incorrect port settings. Make sure that ports 25, 465, or 587 are open on your server. On shared hosting, the SMTP port may be blocked; in this case, contact your hosting support or use the email service provider’s API instead.

Conclusion

In this article, we examined sending email with PHP from two perspectives: the traditional method using the mail() function and the modern, professional method using the PHPMailer library and SMTP.

We also learned how to implement a complete, secure, and visually appealing contact form using PHP and PHPMailer. The key point to always remember is that the mail() function alone is not sufficient for real-world projects, and using SMTP with authentication is the only reliable way to prevent emails from going to spam. If you use WordPress, plugins like WPForms along with an SMTP plugin such as WP Mail SMTP make the process much easier.

Do not forget to always sanitize and validate user inputs to keep your forms secure against XSS and email injection attacks. We hope this article has been helpful and that you can confidently set up your website’s email system and contact form. If you have any questions or encounter a specific error, we would be happy to help you in the comments section. Wishing you success and prosperity. 🙂

Ahura WordPress Theme

The Power to Change Everything

Elementor Page Builder

The most powerful WordPress page builder with 100+ exclusive custom elements.

Incredible Performance

With Ahura’s smart modular loading technology, files load only when they are truly needed.

SEO Optimized for Google

Every line of code is carefully aligned with Google’s algorithms and best practices.

Any questions? Ask here...