How To Send Email Via PHP ?

Its very common that every simple to simple website or one page template have contact us form so people who want to contact they can directly fill the form and send you query and you can do it via PHP. Lets take a look how we can Send Email Via PHP.

How To Send Email Via PHP ?

If you want to write code from scratch its help to get know more about php build-in function like mail(), filter_var() and many more.

Here we create a form of contact us where we use bootstrap version 4.

File Structure

HTML Form in index.php file

HTMLCopy
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Send Mail</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <form method="post">
                <div class="mb-2">
                    <label for="name" class="form-label">Name</label>
                    <input
                            type="text"
                            class="form-control"
                            name="name"
                            id="name">
                </div>
                <div class="mb-2">
                    <label for="email" class="form-label">Email</label>
                    <input
                            type="text"
                            class="form-control"
                            name="email"
                            id="email">
                </div>
                <div class="mb-2">
                    <label for="subject" class="form-label">Subject</label>
                    <input
                            type="text"
                            class="form-control"
                            name="subject"
                            id="subject">
                </div>
                <div class="mb-2">
                    <label for="query" class="form-label">Query</label>
                    <textarea
                            name="query"
                            id="query"
                            class="form-control"></textarea>
                </div>
                <div class="d-grid mb-2">
                    <button
                            type="submit"
                            class="btn btn-primary"
                            name="submit"
                    >Send Mail
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

PHP Code in index.php file

PHPCopy
<?php

if (isset($_POST['submit'])) {

    $name = sanitizeData($_POST['name']);
    $email = filterEmail($_POST['email']);
    $subject = sanitizeData($_POST['subject']);
    $query = sanitizeData($_POST['query']);

    if (checkAllInput($name, $subject, $query) || $email === null) {
        die("Form Data is Invalid");
    }

    $templateData = [
        'name' => $name,
        'email' => $email,
        'subject' => $subject,
        'query' => $query
    ];

    $message = includes('mail-template.php', $templateData, false);

    $to = 'thetestcode[email protected]';

    $headers = "From: " . $email . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";


    mail($to, $subject, $message, $headers);
    echo "Thanks for Contacting Us";
}


function sanitizeData($data): string
{
    return htmlspecialchars(stripslashes(trim($data)));
}

function filterEmail(string $email): ?string
{
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    return filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($email) ? $email : null;
}

function checkAllInput(...$data): bool
{
    foreach ($data as $item) {
        if (empty($item)) {
            return true;
        } else {
            continue;
        }
    }
    return false;
}

function includes(string $file_path, array $data = [], bool $print = true)
{
    $opt = null;
    if (file_exists($file_path)) {
        ob_start();
        extract($data);
        include $file_path;
        $opt = ob_get_clean();
    }
    if ($print)
        print $opt;
    else
        return $opt;
}

Full Code in index.php file

HTMLCopy
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Send Mail</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <form method="post">
                <div class="mb-2">
                    <label for="name" class="form-label">Name</label>
                    <input
                            type="text"
                            class="form-control"
                            name="name"
                            id="name">
                </div>
                <div class="mb-2">
                    <label for="email" class="form-label">Email</label>
                    <input
                            type="text"
                            class="form-control"
                            name="email"
                            id="email">
                </div>
                <div class="mb-2">
                    <label for="subject" class="form-label">Subject</label>
                    <input
                            type="text"
                            class="form-control"
                            name="subject"
                            id="subject">
                </div>
                <div class="mb-2">
                    <label for="query" class="form-label">Query</label>
                    <textarea
                            name="query"
                            id="query"
                            class="form-control"></textarea>
                </div>
                <div class="d-grid mb-2">
                    <button
                            type="submit"
                            class="btn btn-primary"
                            name="submit"
                    >Send Mail
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

<?php

if (isset($_POST['submit'])) {

    $name = sanitizeData($_POST['name']);
    $email = filterEmail($_POST['email']);
    $subject = sanitizeData($_POST['subject']);
    $query = sanitizeData($_POST['query']);

    if (checkAllInput($name, $subject, $query) || $email === null) {
        die("Form Data is Invalid");
    }

    $templateData = [
        'name' => $name,
        'email' => $email,
        'subject' => $subject,
        'query' => $query
    ];

    $message = includes('mail-template.php', $templateData, false);

    $to = '[email protected]';

    $headers = "From: " . $email . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";


    mail($to, $subject, $message, $headers);
    echo "Thanks for Contacting Us";
}


function sanitizeData($data): string
{
    return htmlspecialchars(stripslashes(trim($data)));
}

function filterEmail(string $email): ?string
{
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    return filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($email) ? $email : null;
}

function checkAllInput(...$data): bool
{
    foreach ($data as $item) {
        if (empty($item)) {
            return true;
        } else {
            continue;
        }
    }
    return false;
}

function includes(string $file_path, array $data = [], bool $print = true)
{
    $opt = null;
    if (file_exists($file_path)) {
        ob_start();
        extract($data);
        include $file_path;
        $opt = ob_get_clean();
    }
    if ($print)
        print $opt;
    else
        return $opt;
}

HTML and PHP mix code in mail-template.php

HTMLCopy
<html>
<head>
    <style>
        body {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        .container {
            width: 70%;
            border: 1px solid rgba(0, 0, 0, 0.5);
            padding: 20px;
            margin: 10px auto;
        }

        .query {
            font-family: Arial, Helvetica, sans-serif;
            text-align: center;
        }

        .subject h3 {
            padding-top: 12px;
            padding-bottom: 12px;
            background: #4CAF50;
            color: white;
            border-radius: 15px;
        }

        .contact p {
            background: #ddd;
            padding: 10px;
            border-radius: 15px;
        }

        .site-info {
            padding: 5px 20px;
            width: 70%;
            margin: auto;
            text-align: center;
            background: #ddd;
        }

        .site-info p {
            font-size: 20px;
        }

    </style>
</head>
<body>
<div class="container">
    <div class="query">
        <div class="subject">
            <h3><?php echo $subject ?? "" ?></h3>
        </div>
        <div class="detail">
            <?php echo $query ?? "" ?>
        </div>
        <div class="contact">
            <p>Name - <?php echo $name ?? "Unknown" ?></p>
            <p>Email - <?php echo $email ?? "Unknown" ?></p>
        </div>
    </div>
</div>
<div class="site-info">
    Dump Coder
</div>
</body>
</html>

It’s very simple to make PHP Send Email script. If you stuck somewhere then you can follow video from youtube that is embed below.

Source Code – Github Link

Conclusion

What is say about it ? Its just 5 minute work to make a contact us form with php mail() function. I hope you understand that how you can make a php email template and email sending script

Leave a Reply

Your email address will not be published. Required fields are marked *