Link to home
Start Free TrialLog in
Avatar of JohnMac328
JohnMac328Flag for United States of America

asked on

Help with php contact form with GoDaddy

I have a php email contact form I am trying to get to work with GoDaddy,  I contacted their tech support and after a while they gave me the mail_test.php which gives every configuration they have.  I need help getting the SMTP portion of the mail_test.php to work with my script.  I am including all the info that is needed but let me know what other info is needed.  Any help is appreciated.

Here is my script for the mail contact form
<?php 
if(isset($_POST['submit'])){
    $to = "John@mycompany.com"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $name = $_POST['name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $name . " wrote the following:" . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>
<form action="" id="contactform" method="post"> 
                            <fieldset>                            
                            <input type="text" name="name" class="textfield" id="name" value="" />
                            <label>Name</label>
                            <div class="clear"></div>                            
                            <input type="text" name="email" class="textfield" id="email" value="" />
                            <label>E-mail</label>
                            <div class="clear"></div>                            
                            <input type="text" name="subject" class="textfield" id="subject" value="" />
                            <label>Subject</label>
                            <div class="clear"></div> 
                            <textarea name="message" id="message" class="textarea" cols="2" rows="4"></textarea>
                            <div class="clear"></div> 
                            <label>&nbsp;</label>
                            <input type="submit" name="submit" class="buttoncontact" id="buttonsend" value="Submit" />
                            <span class="loading" style="display: none;">Please wait..</span>
                            <div class="clear"></div>
                            </fieldset> 
                        </form>

Open in new window

John
 mail_test.txt
User generated image
Avatar of David Favor
David Favor
Flag of United States of America image

Best to avoid using GoDaddy outgoing IPs for sending mail. These tend to burn (get blocked) quickly because they're shared between many clients.

Use a true relay service, like Mailgun (first 10K messages free each month).

Then go through the SPF + DKIM + relay setup they provide when you setup an account.

Note: Your config above is very wrong. You should only send outgoing mail on port 25 using Opportunistic TLS (unsure if GoDaddy does this correctly... probably not). Using outgoing port 465... unsure what this means... I suppose if this means you're suppose to submit mail on port 465, then GoDaddy sends mail using port 25 this will work. Very odd config info though.

Best to use MailGun + have your setup work first time... if you're looking to optimize your time + budget + have SMTP mail work 100% of the time, with zero effort on your part.

Note: GoDaddy == Best domain Registrant. GoDaddy == One of the worst hosting companies.
Hi John,

The mail_test script they've send you is basically a form that allows you to select which of the 2 methods you want to use to send email. You can send email through PHP's built-in mail() function, or you can send mail through the 3rd party PHPMailer class. In their form, if you choose SMTP option, then the form will be send using PHPMailer.

If you want to use that, then you should install the PHPMailer classes (https://github.com/PHPMailer/PHPMailer) and use that in your mail script. Easest way to install it is with Composer, but you can manually do it if needed.

Have a look at their test script and towards the end  you'll see how thery're using it. Basically, that's what you need to do in your own script.
Avatar of JohnMac328

ASKER

I wont be sending any mail.  This is just to get mail from people wanting more info.  Do you know how to configure my php mail section to get it to work just to receive incoming mail?  Does not have to be SMTP
Not sure what you mean by not sending any mail - that's the sole purpose of a contact form. It sends mail! When someone on your site fills in a form (name / phone / email / message etc), then the contents of that form are emailed to a defined recipient. You have 2 choices on how to send that email - using the built in mail() function or using the PHPMailer() class.

In the test script above, the SMTP option uses the PHPMailer() class to email the content of the form?

Am I mis-understanding what you need ?
If you're receiving mail, then no of the above config image applies.

You'll simply have an MX record setup for your site, where mail will arrive.

You will never setup any PHP code to receive mail. This is the job of an MTA like Exim4/Postfix/Sendmail.

An MTA will listen on port 25 of your MX IP, receive mail, deposit mail into a server like Dovecot.

You'll then access this mail via a mail client using the POP3 or IMAP4 protocol.

Zero user code, like PHP, for this process.
If you're talking about an opt-in form (your PHP code above suggests this), then you be capturing opt-in form data to a database for later use, so no mail will be involved at all for a normal opt-in process.
David - Sounds like I need to tell them to setup MX - this form just sends me an email with their email - subject - and message.  I have a outlook account that receives the email and I correspond through that.  I did this several years ago with no problem so the MX setup sounds like what needs to happen - I will contact them now
Nope on the incoming MX setup.

If this is true... "this form just sends me an email with their email"... you're talking about mail leaving your machine, not mail arriving at your machine.

In this case, you're back to my suggestion of setting up a real mail relay like MailGun that works (not GoDaddy), which also requires setting up correct SPF + DKIM records... if you expect to receive any mail sent from your form.

You said, "I have a outlook account that receives the email and I correspond through that", which also has very little to do with what you're describing.

You still must setup a mail relay + SPF + DKIM for mail to be accepted by whatever system holds your mail.

Outlook is a mail client, not a mail server. Your mail server is run by some Mailbox Provider, either you or some 3rd party company.
John,

If the form sends email then you'll need to setup your PHP script to send that email out to your email address - this is where the PHPMailer class comes in - the form is submitted (POSTed) to a PHP script. That script then takes the information entered into your form, instantiates the PHPMailer class and generates an email that it sends out to you. You then receive that email in your Outlook mail client.
Chris and David - Good info - I will try composer to see what happens
Ok I went through this tutorial

https://alexwebdevelop.com/phpmailer-tutorial/ - I did the Installing Composer and PHPMailer on Windows (if you use XAMPP, WAMP etc.) portion

and uploaded all the files - here is my script - does this look correct?  Dreamweaver does not like

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

throws a syntax error

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

$email = new PHPMailer(TRUE);
if(isset($_POST['submit'])){
    $to = "John@mycompany.com"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $name = $_POST['name'];
    $subject = "Form submission";
    $message = $name . " wrote the following:" . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>

Open in new window

I guess not - I get this trying to bring up the page

HTTP 500 error
That’s odd... the website can’t display this page
The site may be under maintenance or could have a programming error.
Working with composer won't fix any outgoing email issue.

Generally the way to approach this is...

1) Setup a mail relay account somewhere, like MailGun.

2) You will be provided with DNS records to setup during process.

3) Verify all your DNS records (SPF + DKIM) are correct. If you choose MailGun, they have an online verifier (super handy) to verify your DNS records.

4) Now setup an SMTP port 587 submission credential - host/port/user/pass.

5) Now test #4 using SWAKS.

6) At this point you have working mail, so at this point you know any problems are in your code, rather than mail plumbing.

7) Now proceed onto working out your form code.
For help with your 500 error, provide the complete log entry, which will provide the exact file + line number of problem.

Likely this will be sufficient for you to fix any problems yourself.
Hey John,

OK. First things first - ignore whatever DreamWeaver is telling you. It's not a great program to use for development.

Now, onto your script.

Turn on error reporting right at the start of your script - this will help you debug and it will hilight any problems in your code.

You're passing TRUE into the ctor of the PHPMailer class, which means that any problems with the mailer will throw an exception. This means that you should wrap your code in a try / catch block.

You've gone to the trouble of installing and initialising the PHPMailer class, but then you've decided not to use it all, instead carrying on with the built-in mail() function!

To get things working, I would suggest you start by writing the script to send a simple, static email. This means that you don't have to worry about HTML forms and data validation - that can come later.

Here's a quick demo to get you started. Create this in it's own PHP file and then call it directly in your browser:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require __DIR__ . '/vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->IsSMTP();
    $mail->SMTPAuth = true;
    $mail->Host = "a2plcpnl0816.prod.iad2.secureserver.net"; // check this with your host
    $mail->Port = 465; // check this with your host
    $mail->Username = "email@yourdomain.com"; // check this with your host 
    $mail->Password = "yourPassword"; // check this with your host

    /* Set the mail sender. */
    $mail->setFrom('email@yourdomain.com', 'JohnMac');

   /* Add a recipient. */
   $mail->addAddress('email@yourdomain.com', 'JohnMac');

   /* Set the subject. */
   $mail->Subject = 'Testing the PHPMailer Script';

   /* Set the mail message body. */
   $mail->Body = 'Sending a quick message to see if the PHPMailer script is working OK.';

   /* Finally send the mail. */
   $mail->send();

   echo "email has been sent!";
}
catch (Exception $e)
{
   /* PHPMailer exception. */
   echo $e->errorMessage();
}

Open in new window

First I have to finds out what the correct path is with Godaddy

require __DIR__ . '/vendor/autoload.php';
That path has nothing to do with GoDaddy. It's simply loading the autoload.php file from the vendor folder under the 'current' folder of your script.
Sorry for the delay - I made the changes but the page just has a spinning icon after hitting submit - guess I will have to contact GoDaddy - their support sucks
Hey John,

In a previous comment, I suggested that you write a simple script to generate and send a simple static email (see my code from a few comments ago). The purpose of this is to remove as many moving parts as possible while you're trying to figure things out. In the script I wrote, it just sends an email - nothing more, nothing less. It is not getting bogged down with HTML form tags an submit buttons.

If you try and do too much at once, it makes it more difficult to figure out which part of your program is failing. You said that you get a spinning icon after hitting submit - we have no way of knowing whether that's a form issue / an AJAX issue / a server issue / an email issue - too much is going on.

Try the simple email script and let me know the outcome.
Ok tried just the script and finally got - SMTP Error: Could not authenticate.  I do know that this is correct a2plcpnl0816.prod.iad2.secureserver.net because it was displayed in their test email to me.  The Username is the email for the email account and I put the email password for the password - not the regular Godaddy username and pw
Far better to test this with SWAKS rather than user code.

SWAKS produces a human readable log of the entire SMTP conversation, which can normally pinpoint the problem at a glance.
According to GoDaddy docs, port 465 submission can only be done via SSL (not recommended) or TLS (recommended).

There is no provision for plain text (non SSL/TLS) message submission.

To get your mail submission working, you'll add TLS connection setup to your code.

In fact, you might even use a tool like SWAKS for mail injection, rather than adding the TLS code.

There's another simple way to handle this too.

Just install http://brianstafford.info/libesmtp/ + setup a 4x line config file, then relay all your mail through ESMTPD.

Normally the package to install is called esmtp on most Distros.
Now then... you might be asking yourself... "Why didn't GoDaddy support mention this..."

Well... They're seriously clueless.
Apologies on missing this. I should have checked their docs about mail submission first... to check requirements...

I mistakenly imagined GoDaddy support would have mentioned this, if SSL/TLS were forced as a requirement.
Right. Just done a quick google, and you'll need to use TLS security on port 587, so try with the following config details:

$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;  
$mail->Host = "a2plcpnl0816.prod.iad2.secureserver.net"; // check this with your host
$mail->Username = "email@yourdomain.com"; // check this with your host 
$mail->Password = "yourPassword"; // check this with your host

Open in new window

I still get the SMTP Error: Could not connect to SMTP host.

In the morning I will get with GoDaddy and show them this and ask what the problem is.
Speak to Godaddy - sounds like your config details are probably not correct (host / user / pass)
They could never figure out why the script you sent would not work.  They keep giving me their test script which I included in my original question.  It uses phpmailer which I have no problem with. I was able to cut it down to this amount which works but also has extra stuff with a results panel that shows if the email was successful etc.  What I need is the extra stripped out to just leave the mail form that will send email.

<?php 
if ( isset($_SERVER["OS"]) && $_SERVER["OS"] == "Windows_NT" ) {
    $hostname = strtolower($_SERVER["COMPUTERNAME"]);
} else {
    $hostname = `hostname`;
    $hostnamearray = explode('.', $hostname);
    $hostname = $hostnamearray[0];
}
 
if ( isset($_REQUEST['sendemail']) ) {
    header("Content-Type: text/plain");
    header("X-Node: $hostname");
    $from = $_REQUEST['from'];
    $toemail = $_REQUEST['toemail'];
    $subject = $_REQUEST['subject'];
    $message = $_REQUEST['message'];
    if ( $from == "" || $toemail == "" ) {
        header("HTTP/1.1 500 WhatAreYouDoing");
        header("Content-Type: text/plain");
        echo 'FAIL: You must fill in From: and To: fields.';
        exit;
    }
    if ( $_REQUEST['sendmethod'] == "mail" ) {
        $result = mail($toemail, $subject, $message, "From: $from" );
        if ( $result ) {
            echo 'OK';
        } else {
            echo 'FAIL';
        }
    } elseif ( $_REQUEST['sendmethod'] == "smtp" ) {
        ob_start(); //start capturing output buffer because we want to change output to html
 
        $mail = new PHPMailer;
 
        $mail->SMTPDebug = 2;
        $mail->IsSMTP();
        if ( strpos($hostname, 'cpnl') === FALSE ) //if not cPanel
            $mail->Host = 'relay-hosting.secureserver.net';
        else
            $mail->Host = 'localhost';
        $mail->SMTPAuth = false;
 
        $mail->From = $from;
        $mail->FromName = 'Mailer';
        $mail->AddAddress($toemail);
 
        $mail->Subject = $subject;
        $mail->Body = $message;
 
        $mailresult = $mail->Send();
        $mailconversation = nl2br(htmlspecialchars(ob_get_clean())); //captures the output of PHPMailer and htmlizes it
        if ( !$mailresult ) {
            echo 'FAIL: ' . $mail->ErrorInfo . '<br />' . $mailconversation;
        } else {
            echo $mailconversation;
        }
    } elseif ( $_REQUEST['sendmethod'] == "sendmail" ) {
        $cmd = "cat - << EOF | /usr/sbin/sendmail -t 2>&1\nto:$toemail\nfrom:$from\nsubject:$subject\n\n$message\n\nEOF\n";
        $mailresult = shell_exec($cmd);
        if ( $mailresult == '' ) { //A blank result is usually successful
            echo 'OK';
        } else {
            echo "The sendmail command returned what appears to be an error: " . $mailresult . "<br />\n<br />";
        }
    } else {
        echo 'FAIL (Invalid sendmethod variable in POST data)';
    }
    exit;
}
?><!DOCTYPE html>
<html>
<head>
<title>Mail Test</title>
<style>
td {
    vertical-align: top;
}
</style>
</head>
<body>
<h1>Mail Test</h1>
 
<form id="mailform" name="mailform">
    To: <input value="" name="toemail" type="text" size="40" /><br />
    From: <input value="" name="from" type="text" size="40" /><br />
    Subject: <input name="subject" type="text" disabled size="40" />
    auto <input type="checkbox" onchange="AutoSubject();" name="autosubject" checked><br />
    Message:<br />
    <textarea name="message" rows="15" cols="40">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed tempor incididunt ut labore et dolore magna aliqua. </textarea><br />
    <button type="button" id="sendemail" onclick="GoSend(); AutoSubject();">Send</button>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Method&nbsp;<select onchange="AutoSubject();" name="sendmethod" >
        <option value="mail">PHP mail()</option>
        <option value="smtp">SMTP</option>
<?   if ( !isset($_SERVER["OS"]) && $_SERVER["OS"] != "Windows_NT" ) { ?>
        <option value="sendmail">sendmail from shell</option><? } ?>
 
    </select>
</form>
<br /><br />
 
<hr>
 
<table id="msglog" border="1" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="100%" cellpadding="3" cellspacing="3">
    <tr>
        <td>#</td>
        <td>TIME</td>
        <td>TO</td>
        <td>FROM</td>
        <td>SUBJECT</td>
        <td>MESSAGE</td>
        <td>METHOD</td>
        <td>NODE</td>
        <td>RESULT</td>
    </tr>
</table>
 
<script>
var msgid = 1;
AutoSubject();
 
function AutoSubject() {
    if ( document.mailform.autosubject.checked ) {
        document.mailform.subject.disabled=true;
        document.mailform.subject.value='Test email using '+document.mailform.sendmethod.value+' #'+msgid;
    } else {
        document.mailform.subject.disabled=false;
    }
}
 
function GoSend() {
    var table=document.getElementById("msglog");
    var row = table.insertRow(1);
     
    var NUMcell = row.insertCell(0);
    NUMcell.innerHTML=msgid++;
     
    var DATEcell = row.insertCell(1);
    var d = new Date();
    DATEcell.innerHTML=d.toLocaleTimeString();
     
    var TOcell = row.insertCell(2);
    TOcell.innerHTML=document.mailform.toemail.value;
     
    var FROMcell = row.insertCell(3);
    FROMcell.innerHTML=document.mailform.from.value;
     
    var SUBJECTcell = row.insertCell(4);
    SUBJECTcell.innerHTML=document.mailform.subject.value;
     
    var MESSAGEcell = row.insertCell(5);
    MESSAGEcell.innerHTML=document.mailform.message.value;
     
    var METHODcell = row.insertCell(6);
    METHODcell.innerHTML=document.mailform.sendmethod.value;
     
    var NODEcell = row.insertCell(7);
     
    var RESULTcell = row.insertCell(8);
    RESULTcell.innerHTML="<img height=\"24\" src=\"data:image/gif;base64,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\">";
     
    var postdata= "sendemail=1&toemail="+document.mailform.toemail.value;
        postdata+="&from="+document.mailform.from.value;
        postdata+="&subject="+document.mailform.subject.value;
        postdata+="&sendmethod="+document.mailform.sendmethod.value;
        postdata+="&message="+encodeURIComponent(document.mailform.message.value).replace("%20", "+");
    var url="<?=$_SERVER['PHP_SELF']; ?>";
    var request=new XMLHttpRequest();
    request.open("POST",url,true);
    request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    request.overrideMimeType("text/plain");
    request.onreadystatechange=function() {
        if ( request.readyState==4 ) {
            NODEcell.innerHTML=request.getResponseHeader("X-Node");
            if ( request.responseText == "OK" || request.responseText == "FAIL" ) {
                RESULTcell.innerHTML=request.responseText;
            } else {
                if ( request.status == 0 ) {
                    RESULTcell.innerHTML="ERR_EMPTY_RESPONSE";
                } else {
                    RESULTcell.innerHTML="HTTP/1.1 "+request.status+" "+request.statusText+"<br /><br />"+request.responseText;
                }
            }
        }
    }
    request.send(postdata);
}
</script>

Open in new window

OK. First off, create a simple form with the details you need and point the action to your php script:

<form method="post" action="sendmail.php">
    <div>
        <label for="from">From</label>
        <input type="text" name="from" id="from">
    </div>

    <div>
        <label for="toeamil">To</label>
        <input type="text" name="toemail" id="toemail">
    </div>

    <div>
        <label for="subject">Subject</label>
        <input type="text" name="subject" id="subject">
    </div>

    <div>
        <label for="message">Message</label>
        <textarea name="message" id="message"></textarea>
    </div>
    
    <div>
        <input type="submit" name="submit" value="Send">
    </div>
</form>

Open in new window

Now take a look at the following. It's a stripped down version of the PHP scrip that they've provided you with. Save it with the same name that you've set the form action to and try submitting the form to see what you get:

<?php 
if ( isset($_SERVER["OS"]) && $_SERVER["OS"] == "Windows_NT" ) {
    $hostname = strtolower($_SERVER["COMPUTERNAME"]);
} else {
    $hostname = `hostname`;
    $hostnamearray = explode('.', $hostname);
    $hostname = $hostnamearray[0];
}

header("Content-Type: text/plain");
header("X-Node: $hostname");
$from = $_POST['from'];
$toemail = $_POST['toemail'];
$subject = $_POST['subject'];
$message = $_POST['message'];

// Validate the from and to addresses
if ( $from == "" || $toemail == "" ) {
    header("HTTP/1.1 500 WhatAreYouDoing");
    header("Content-Type: text/plain");
    echo 'FAIL: You must fill in From: and To: fields.';
    exit;
}

ob_start(); //start capturing output buffer because we want to change output to html
 
$mail = new PHPMailer;
 
$mail->SMTPDebug = 2;
$mail->IsSMTP();

if ( strpos($hostname, 'cpnl') === FALSE ) { //if not cPanel
    $mail->Host = 'relay-hosting.secureserver.net';
} else {
    $mail->Host = 'localhost';
}

$mail->SMTPAuth = false;
$mail->From = $from;
$mail->FromName = 'Mailer';
$mail->AddAddress($toemail);

$mail->Subject = $subject;
$mail->Body = $message;

$mailresult = $mail->Send();
$mailconversation = nl2br(htmlspecialchars(ob_get_clean())); //captures the output of PHPMailer and htmlizes it

if ( !$mailresult ) {
    echo 'FAIL: ' . $mail->ErrorInfo . '<br />' . $mailconversation;
} else {
    echo $mailconversation;
}

exit;

Open in new window

Ok thanks, Godaddy is blocked at work so I will try when I get home.
It bombed on sendmail.php with this
This page isn’t working www.mycompany.com is currently unable to handle this request.
HTTP ERROR 500
sendmail.php
send.php
OK. We need to turn on error reporting. You'll do that right at the start of the sendmail.php script:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ( isset($_SERVER["OS"]) && $_SERVER["OS"] == "Windows_NT" ) {
   ...

Open in new window

You should also change your HTML page to use HMTL5. Using HTML4 is proper old-school :)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Send EMail</title>
    </head>

    <body>
        <form method="post" action="sendmail.php">
            <div>
                <label for="from">From</label>
                <input type="text" name="from" id="from">
            </div>

            <div>
                <label for="toeamil">To</label>
                <input type="text" name="toemail" id="toemail">
            </div>

            <div>
                <label for="subject">Subject</label>
                <input type="text" name="subject" id="subject">
            </div>

            <div>
                <label for="message">Message</label>
                <textarea name="message" id="message"></textarea>
            </div>
            
            <div>
                <input type="submit" name="submit" value="Send">
            </div>
        </form>
    </body>
</html>

Open in new window

Just out of interest, what version of PHP are you running. You really need to be running version 7.x.x.

There's also nothing in your code that sets up the PHPMailer classes. You would need to include the PHPMailer scripts, but how you do that will depend on your setup. If you installed PHPMailer with composer, then just include the Autoloader. If you manually installed it, then you'd need to include (require) the files manually:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

Open in new window

Just curious as to why the form worked with all the extra garbage but now it doesn't.  As for PHP this is running on GoDaddy platform so what ever they are using.
When you had all the other Garbage in your script, there was an option on the form to choose which method you used for sending the email (mail / smtp / sendmail). This option would have been chosen from the dropdown (<option>).  The default option would have been mail, so if you didn't change that, then the email would have been sent out using PHP's in-built mail() function. It would only have tried to use the PHPMailer class if your chose 'smtp' from the dropdown.

You said in an earlier comment that it used PHPMailer, so I assumed you'd tested it with that. In the first script you posted, the lines to include PHPMailer were already in place - you were loading them by requiring the autoloader. If you want to use PHPMailer, then you're going to need to include that in your script (and make sure you've installed PHPMailer with Composer)

As for the PHP version, for any kind of development, you really need to understand the platform your developing on. Trying to guess the development environment by using 'whatever GoDaddy are using' is just a massive problem waiting to happen. If they're still using PHP 5, then you need to get that updated ASAP. If they won't update it, change hosts ... seriously !

Easiest way to get a handle on your server environment is to create a simple PHP file containing the following:

<php phpinfo();

Open in new window


Load the file up in your browser and it will show you all the information you need.
A couple of things.  The SMTP option in the dropdown never worked and Godaddy could not figure out why.  They said "its not like a real server" so that is why I don't think your code will work.  The code is correct but it wont work on their server. And trouble shooting would be a waste of time.  That is why I thought the best way to get the mail working was to take what works and fit it into the form without all the extra garbage.  I will run the php script when i get home to see what version they are running.
PHP version is 7.2
Hmmm. You say the SMTP option in the test script never worked and GoDaddy couldn't figure out why!

That would cause me to have huge reservations about GoDaddy (as most developers already do). Their own test script won't work on their own servers, and they don't know why. Very poor!

And if they're saying that their hosting accounts are not like a real server - Run

If you have the option of switching hosting companies, now would be the time to do that. If you're serious about development, then you need a proper hosting account ... and GoDaddy is clearly not that.

If you really want to stick with GoDaddy, and want to persist with using the mail() function, then the important part of the script is this:

$from = $_POST['from'];
$toemail = $_POST['toemail'];
$subject = $_POST['subject'];
$message = $_POST['message'];
        
$result = mail($toemail, $subject, $message, "From: $from" );

if ( $result ) {
    echo 'OK';
} else {
    echo 'FAIL';
}

Open in new window

Create an HTML form and POST to that script. It may send your email, but I would suggest that it's not safe, it's not secure, it's not flexible and it's highly likely that any email sent from it will end up being flagged as spam. It's also open for abuse. Use at your own peril!
Yeah I hear ya.  Years ago I had no problems with them. Already paid so what I am thinking is get this working then find another hosting company.  What hosting company do you like?
As Chris said, "That would cause me to have huge reservations about GoDaddy (as most developers already do). Their own test script won't work on their own servers, and they don't know why. Very poor!"

This is very typical of GoDaddy.

As for other hosting, if you'd like full control + solid hardware, look at https://ovh.com pricing.
$70 per month?  Not budgeted for that.
You don't need a dedicated server for this. You just need a relatively simple hosting package from a company that know's what it's doing and can offer you the support you need. GoDaddy it seems aim their products at click-and-go WebDevs, so aren't equipped for customers who actually want to do some proper development.

I can't really give you any advice on a good host. I'm based in the UK, and I offer my own CentOS / Plesk hosting accounts to my customers. If you're in the UK, feel free to get in touch.
So going back to the original question how would it all fit together here?

<?php 
if(isset($_POST['submit'])){
    $to = "John@mycompany.com"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $name = $_POST['name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $name . " wrote the following:" . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>
<form action="" id="contactform" method="post"> 
                            <fieldset>                            
                            <input type="text" name="name" class="textfield" id="name" value="" />
                            <label>Name</label>
                            <div class="clear"></div>                            
                            <input type="text" name="email" class="textfield" id="email" value="" />
                            <label>E-mail</label>
                            <div class="clear"></div>                            
                            <input type="text" name="subject" class="textfield" id="subject" value="" />
                            <label>Subject</label>
                            <div class="clear"></div> 
                            <textarea name="message" id="message" class="textarea" cols="2" rows="4"></textarea>
                            <div class="clear"></div> 
                            <label>&nbsp;</label>
                            <input type="submit" name="submit" class="buttoncontact" id="buttonsend" value="Submit" />
                            <span class="loading" style="display: none;">Please wait..</span>
                            <div class="clear"></div>
                            </fieldset> 
                        </form>

Open in new window

The code you've got there is the basic way of sending mail with PHPs built-in mail() function. There's not really much more to it than that. Your originaly question was about getting the SMTP portion working, which is why we went down the route of PHPMailer.

If you can't get PHPMailer working, then you can't send SMTP mail - you're left with the simple, basic mail() function. I'd advise against that but if  that's all you've got, then you may not have any other choice.

As your code stands, it's highly likely that your form will be used to mass mail out a huge amount of SPAM. Anyone (including bots) can type any address into your form with any message and have that mail delivered to that address !!
True, I am just taking this a step at a time. Once I get it working with the above code to at least receive the messages from people sent to me, I will then add some captcha  for security.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.