[Help] Why isn't my sendmail working?

the mail() function

Moderators: egami, macek, gesf

Post Reply
g0dtier
New php-forum User
New php-forum User
Posts: 4
Joined: Thu Feb 27, 2020 4:36 am


Hi guys I'm seriously stressing hard about this. I seem to have written everything properly but my contact form just won't send an e-mail and update the status on my webpage. I fill out the details on my contact form and my status text stays on "Email is sending...". I'd REALLY REALLY appreciate any help you could toss my way. Thanks a ton!

sendmail.php

Code: Select all

<?php
$name       = @trim(stripslashes($_POST['name'])); 
$from       = @trim(stripslashes($_POST['email'])); 
$subject    = @trim(stripslashes($_POST['subject'])); 
$message    = @trim(stripslashes($_POST['message'])); 
$to   		= 'myemail@gmail.com';//replace with your email

$headers   = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

mail($to, $subject, $message, $headers);

die();
?>
main.js

Code: Select all

//Contact Form
	var form = $('#contact-form');
	form.submit(function(event){
		event.preventDefault();
		var form_status = $('.form-status');
		$.ajax({
			url: $(this).attr('action'),
			beforeSend: function(){
				form_status.find('.form-status-content').html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn();
			}
		}).done(function(data){
			form_status.find('.form-status-content').html('<p class="text-success">Thank you for contact us. As early as possible  we will contact you</p>').delay(3000).fadeOut();
		});
	});
contact.html

Code: Select all

<form class="form-horizontal" id="contact-form" role="form">
                                <div class="form-group form-status">
                                    <div class="col-sm-offset-2 col-sm-6">
                                        <div class="form-status-content">
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-offset-2 col-sm-6">
                                        <input type="text" name="name" class="form-control input-lg" placeholder="Name" required="required">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-offset-2 col-sm-6">
                                        <input type="email" name="email" class="form-control input-lg" placeholder="Email" required="required">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-offset-2 col-sm-6">
                                        <input type="text" name="subject" class="form-control input-lg" placeholder="Subject" required="required">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-offset-2 col-sm-8">
                                        <textarea name="message" rows="6" class="form-control input-lg" placeholder="Message" required="required">	         </textarea>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-offset-2 col-sm-8">
                                        <button type="submit" class="btn btn-lg btn-transparent">Submit</button>
                                    </div>
                                </div>
                            </form>

g0dtier
New php-forum User
New php-forum User
Posts: 4
Joined: Thu Feb 27, 2020 4:36 am

Okay so now that status text "E-mail sent we'll contact you soon" but there is no e-mail sent. I logged (data) in main.js and no errors appear.

Edit2: My website is and navigate to the Contact page.

I'm flabbergasted I have no idea why it won't send.
User avatar
augustowloch
New php-forum User
New php-forum User
Posts: 9
Joined: Sun Feb 23, 2020 7:26 am
Location: Buenos Aires, Argentina
Contact:

try instead of die() in the php, to return a HTML 200 OK
g0dtier
New php-forum User
New php-forum User
Posts: 4
Joined: Thu Feb 27, 2020 4:36 am

changed to return; and still nothing

Code: Select all

<?php
$name       = @trim(stripslashes($_POST['name'])); 
$from       = @trim(stripslashes($_POST['email'])); 
$subject    = @trim(stripslashes($_POST['subject'])); 
$message    = @trim(stripslashes($_POST['message'])); 
$to   		= 'j0sh.all3n@gmail.com';//replace with your email

$headers   = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

mail($to, $subject, $message, $headers);

return;
?>
Any way to put an error logging code in there and how to do that? Sorry im completely new to all this. Thanks for your help though I really, really appreciate it. Seriously do.
User avatar
augustowloch
New php-forum User
New php-forum User
Posts: 9
Joined: Sun Feb 23, 2020 7:26 am
Location: Buenos Aires, Argentina
Contact:

try:

Code: Select all

http_response_code(200); 
die();
check please in browser inspector what is the response of the php in the ajax call!
g0dtier
New php-forum User
New php-forum User
Posts: 4
Joined: Thu Feb 27, 2020 4:36 am

Nothing. Lol.

I'm going to get rid of mail() and using something else. I'll post back if I can get a friggin e-mail sent with my contact form...
crazymhegde
New php-forum User
New php-forum User
Posts: 1
Joined: Fri Apr 10, 2020 11:03 pm

it is not working
User avatar
Strider64
php-forum GURU
php-forum GURU
Posts: 429
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Save yourself a bunch a headaches and just use a third-party mailer such as PHPMailer or SwiftMailer (I use this one). The sending it is easy to do.


An example -

Form

Code: Select all

<?php
require_once 'assets/config/config.php';
require_once "vendor/autoload.php";

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=yes, initial-scale=1.0">
    <title>Contact Form</title>
    <link rel="stylesheet" media="all" href="assets/css/styles.css">
</head>
<body class="site">
<div id="skip"><a href="#content">Skip to Main Content</a></div>
<header class="masthead">

</header>

<?php include_once "assets/includes/inc.nav.php"; ?>

<main id="content" class="checkStyle">
    <div id="message">
        <h2 id="notice">Form Notification</h2>
    </div>
    <form id="contact" name="contact" action="contact.php" method="post" autocomplete="on">

        <input id="token" type="hidden" name="token" value="<?= $_SESSION['token'] ?>">
        <label class="labelstyle" for="name" accesskey="U">Contact Name</label>
        <input name="name" type="text" id="name" tabindex="1" autofocus required="required"/>

        <label class="labelstyle" for="email" accesskey="E">Email</label>
        <input name="email" type="email" id="email" tabindex="2" required="required"/>

        <label class="labelstyle" for="phone" accesskey="P">Phone <small>(optional)</small></label>
        <input name="phone" type="tel" id="phone" tabindex="3">

        <label class="labelstyle" for="web" accesskey="W">Website <small>(optional)</small></label>
        <input name="website" type="text" id="web" tabindex="4">

        <label for="message-type">Reason for Writing?</label>
        <select id="message-type" name="reason">
            <option value="message">Message</option>
            <option value="inquiry">Inquiry</option>
            <option value="order">Order</option>
        </select>

        <label class="textareaLabel" for="comments">Comments Length:<span id="length"></span></label>
        <textarea name="comments" id="comments" spellcheck="true" placeholder="Enter Message Here..." tabindex="6"
                  required="required"></textarea>
        <button id="submitForm" type="submit" name="submit" value="Submit" tabindex="7" data-response="">Submit</button>
        <!-- Use a data callback function that Google provides -->
        <div id="recaptcha" class="g-recaptcha" data-sitekey="6Le0QrobAAAAAGDacgiAr1UbkPmj0i-LFyWXocfg"
             data-callback="correctCaptcha"></div>



    </form>
</main>

<div class="sidebar">

</div>

<footer class="colophon">
    <p>&copy; <?php echo date("Y") ?> The Miniature Photographer</p>
</footer>
<script src="assets/js/contact.js" async defer></script>
<!-- Fetch the g-response using a callback function -->
<script>
    function correctCaptcha(response) {
        document.querySelector('#submitForm').setAttribute('data-response', response);
    }
</script>

<script src='https://www.google.com/recaptcha/api.js' async defer></script>
</body>
</html>
Vanilla JavaScript

Code: Select all

'use strict';
/* Convert RGBa to HEX  */
const rgba2hex = (orig) => {
    let a,
        rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
        alpha = (rgb && rgb[4] || "").trim(),
        hex = rgb ?
            (rgb[1] | 1 << 8).toString(16).slice(1) +
            (rgb[2] | 1 << 8).toString(16).slice(1) +
            (rgb[3] | 1 << 8).toString(16).slice(1) : orig;

    if (alpha !== "") {
        a = alpha;
    } else {
        a = "01";
    }
    // multiply before convert to HEX
    a = ((a * 255) | 1 << 8).toString(16).slice(1);
    hex = hex + a;

    return hex;
};

const myColor = (colorcode) => {
    let hexColor = rgba2hex(colorcode);
    return '#' + hexColor;
};

/*
 * Constants & Variables Initialization Section.
 */
const myGreen = myColor("rgba(29, 100, 31, 0.70)"); /* Green with 70% transparency */
const myRed = myColor("rgba(84, 0, 30, 0.50)"); /* Red with 70% transparency */
const myBorder = myColor("rgba(85, 85, 85, 1.00");
const contact = () => {
    const d = document;
    const sendUrl = 'sendMsg.php';
    const submit = d.querySelector('#submitForm');
    const radioBtn = d.querySelector('#message-type');
    const buttons = d.getElementsByName("reason");
    const message = d.querySelector('#message');
    const messageSuccess = d.querySelector('#messageSuccess');

    let name = d.querySelector('#name');
    let email = d.querySelector('#email');
    let phone = d.querySelector('#phone');
    let website = d.querySelector('#web');
    let notice = d.querySelector('#notice');
    let sendEmail = {};
    let sendStatus = {
        name: false,
        email: false,
        comments: false
    };
    sendEmail.reason = 'message';
    sendEmail.token = d.querySelector('#token').value;

    message.style.display = "none";

    let comments = d.querySelector("textarea");
    let output = d.querySelector("#length");

    //d.getElementById('contact').scrollIntoView();


    name.addEventListener('input', () => {
        const value = name.value.trim();

        if (value) {
            name.style.borderColor = myBorder;
            sendEmail.name = name.value;
            sendStatus.name = true;
        } else {
            name.style.borderColor = "red";
            name.value = "";
            name.placeholder = "Name Required";
            name.focus();

        }

    });

    const emailIsValid = (email) => {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    };

    email.addEventListener('change', () => {
        let status = emailIsValid(email.value);
        console.log('Email Address', email.value, 'Status', status);
        if (!status) {
            email.value = "";
            email.placeholder = "Email Address is Invalid!";
            email.style.borderColor = "red";
            email.focus();
        } else {
            email.style.borderColor = myBorder;
            sendEmail.email = email.value;
            sendStatus.email = true;
        }
    });


    /*
     * Selection Element
     */
    buttons.forEach((value, index) => {
        //console.log(value, index);
        buttons[index].addEventListener('change', (e) => {
            sendEmail.reason = e.target.value;
            //console.log('Reason:', sendEmail.reason);
        });
    });


    comments.addEventListener("input", () => {
        // noinspection JSValidateTypes
        output.textContent = comments.value.length;
        const value = comments.value.trim();

        if (value) {
            comments.style.borderColor = myBorder;
            sendEmail.comments = comments.value;
            sendStatus.comments = true;
        } else {
            comments.style.borderColor = "red";
            comments.placeholder = "Message Required!";
            comments.focus();
        }
    });


    /* Success function utilizing FETCH */
    const sendUISuccess = function (result) {
        //console.log('Result', result);
        if (result) {
            d.querySelector('#recaptcha').style.display = "none";
            submit.style.display = "none";
            notice.style.display = "grid";

            notice.textContent = "Email Successfully Sent!";
            notice.style.color = "green";
            message.style.display = "grid";
            //messageSuccess.style.display = "block";
            d.querySelectorAll('form > *').forEach(function (a) {
                a.disabled = true;
            });
        }
    };

    /* If Database Table fails to update data in mysql table */
    const sendUIError = function (error) {
        console.log("Database Table did not load", error);
    };

    const handleSaveErrors = function (response) {
        if (!response.ok) {
            throw (response.status + ' : ' + response.statusText);
        }
        return response.json();
    };

    const saveRequest = (sendUrl, succeed, fail) => {

        fetch(sendUrl, {
            method: 'POST', // or 'PUT'
            body: JSON.stringify(sendEmail)

        })
            .then((response) => handleSaveErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
    };

    submit.addEventListener('click', (e) => {
        e.preventDefault();
        sendEmail.phone = phone.value;
        sendEmail.website = website.value;
        sendEmail.response = submit.getAttribute('data-response');
        if (email.value === '') {
            email.placeholder = "Email Address is Invalid!";
            email.style.borderColor = "red";
            email.focus();
        }
        if (sendStatus.name && sendStatus.email && sendStatus.comments) {
            saveRequest(sendUrl, sendUISuccess, sendUIError);
        } else {
            notice.style.display = "block";
            notice.textContent = "Name, Email, and Message Required!";
        }
    }, false);


};


contact();
The PHP Portion of it

Code: Select all

<?php

require_once 'assets/config/config.php';
require_once "vendor/autoload.php";

use PhotoTech\sendMail;

/*
 * The below must be used in order for the json to be decoded properly.
 */
$data = json_decode(file_get_contents('php://input'), true);

$token = $data['token'];

if (hash_equals($_SESSION['token'], $data['token'])) {
    /* The Following to get response back from Google recaptcha */
    $url = "https://www.google.com/recaptcha/api/siteverify";

    $remoteServer = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_SANITIZE_URL);
    /*
     * g-response is from $data['response'] that was sent over using FETCH
     */
    $response = file_get_contents($url . "?secret=". PRIVATE_KEY . "&response=" . $data['response'] . "&remoteip=" . $remoteServer);
    $recaptcha_data = json_decode($response);
    /* The actual check of the recaptcha */
    if (isset($recaptcha_data->success) && $recaptcha_data->success === TRUE) {
        /*
         * If token matches and ReCaptcha is valid then send to an email
         * php script or php class. I personally use Swiftmailer, but you can use
         * another 3rd Party Mailer or write you own email script (I wouldn't
         * recommend it).
         */
        $data['message'] =
            '<html lang="en">' .
            '<body style=\'background: #eee;\'>' .
            '<p style="font-size: 1.8em; line-height: 1.5;">' . $data['name'] . '<br>' . $data['email'] . '<br>' . $data['phone'] . '<br>' . $data['website'] . '<br> Subject of Email is ' . $data['reason'] . '</p>' .
            '<p style="font-size: 1.6em; line-height: 1.5;">' . $data['comments'] . '</p>' .
            '<p style="font-size: 1.4em; line-height: 1.5;">Thank You, for taking your time to contact me! I will get back to you as soon as I can.<br> Best regards, John Pepp</p>' .
            '</body>' .
            '</html>';
        $send = new sendMail();

        $result = $send->sendEmail($data);

        /* Send Back Result (true or false) back to Fetch */
        if ($result) {
            output(true);
        } else {
            errorOutput(false);
        }
    } else {
        $success = "You're not a human!"; // Not on a production server:
    }
} else {
    output('Token Error');
}

function errorOutput($output, $code = 500) {
    http_response_code($code);
    echo json_encode($output);
}


/*
 * After converting data array to JSON send back to javascript using
 * this function.
 */
function output($output) {
    http_response_code(200);
    echo json_encode($output);
}
Life is a fig newton of your imagination! https://www.phototechguru.com/
Post Reply