Jump to content

PHP contact form sending to email via smtp authentication


bethlou

Recommended Posts

Hi

 

I am very new to PHP. I'm wanting a feedback form on my website where the form is sent via SMTP rather than sendmail.

I have checked that php is working by doing this code:

 

<?php

error_reporting(E_ALL);
ini_set('display_errors', True);

$path = '/home/****/php';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

echo("<p>Sending PEAR Mail.php...</p>");

require('Mail.php');

$from = "Info <info@***.co.uk>";
$to = "Info <info@***.co.uk>";
$subject = "Hi - Test message!";
$body = "Hi,\n\nHow are you?";

$host = "mail.***.co.uk";
$username = "info@***.co.uk";
$password = "***";

$headers = array ('From' => $from,
   'To' => $to,
   'Subject' => $subject);
$smtp = Mail::factory('smtp',
   array ('host' => $host,
     'auth' => true,
     'username' => $username,
     'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
   echo("<p>" . $mail->getMessage() . "</p>");
  } else {
   echo("<p>Message successfully sent!</p>");
  }
?>

 

This works fine.

 

I then created a form in my contact page:

 

<form name="feedbackform" action="form-mailer2.php" method="post">
	<input type="hidden" name="Required" value="Name,Comments">
	<p>Name: <input name="Name" size="30"> <span class="formsmall">required</span></p>
<p>E-mail: <input name="Email" size="30"> <span class="formsmall">optional</span></p>
<p>Feedback/Comments:</p>
<p><textarea name="Comments" rows="5" cols="40"></textarea></p>
<p><input type="submit" value="Submit" name="submitform"><input type="reset" value="Reset" name="reset"></p>
</form>

 

 

I then used the code based on the php initial example and the code file that would get the form details from the contact page and send to the email address via smtp. I have left the validations in - although if these are no good please feel free to tell me! I will want to put a captcha in but need to look into that yet.

 

Anyway, the code I have created is now this (which is saved in the file form-mailer2.php):

 

<?php       

error_reporting(E_ALL);
ini_set('display_errors', True);

$path = '/home/****/php';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

echo("<p>Sending PEAR Mail.php...</p>");

require('Mail.php');

$mailfrom = "info@***.co.uk";
$mailTo = "info@***.co.uk"; 
$mailSubject = "Web Feedback"; 
$mailHost = "mail.***.co.uk"; 
$mailPort = "25"; 
$mailAuth = "true"; 
$mailPassword = "****"; 

// Get the form fields.
$name = $_POST['Name'];
$email = $_POST['Email'];
$comments = $_POST['Comments'];
$reqFields = $_POST['Required'];

// I find including the time/date useful for record-keeping.
// Note that it is the web server's time/date, not yours
// or the sender's.
$date = date("l jS F Y, g:i A");

// A simple yet reasonably effective email address validator.
if ((!ereg(".+\@.+\..+", $email)) || (!ereg("^[a-zA-Z0-9_@.-]+$", $email))) {
	$errorMessages .= "<li>Invalid email address: $email</li>";
}

// Make sure required fields are filled in.
$checkFields = explode(",",$reqFields);
while(list($theField) = each($checkFields)) {
	if(!$$checkFields[$theField]) {
		$errorMessages .= "<li>Missing $checkFields[$theField]</li>";
	}
}

// If there are errors, display them and a back button.
if($errorMessages) { ?>
	<p>Errors were found on the form.</p>
	<ul>
		<?php echo $errorMessages; ?>
	</ul>
	<p><input type="button" value="Back" onClick="history.back()"></p>
	<?php
}
// No errors, send the message and print out success message.
else {


	// Build the email.
	$body = "            Name: $Name
           Email: $Email
           Phone: $Phone

----- Comments -----
$Comments
--------------------
       



	$headers["From"]    = $mailTo;
	$headers["To"]      = $mailTo;
	$headers["Subject"] = $mailSubject;
	$params["host"] = $mailHost;
	$params["port"] = $mailPort;
	$params["auth"] = $mailAuth;
	$params["username"] = $mailTo;
	$params["password"] = $mailPassword;
     
      $headers = array ('From' => $from,
   'To' => $to,
   'Subject' => $subject);
$smtp = Mail::factory('smtp',
   array ('host' => $host,
     'auth' => true,
     'username' => $username,
     'password' => $password));

$mail = $smtp->send($mailTo, $headers, $body);

if (PEAR::isError($mail)) {
   echo("<p>" . $mail->getMessage() . "</p>");
  } else {
   echo("<p>Message successfully sent!</p>");
  }
//  I would rather redirect to a different thank you page but both of next options don't work when taking out:    echo("<p>Message successfully sent!</p>"); 
//RedirectToURL("thank-you.php");   or  header(Location: "thank-you.php" );  


?>

 

 

Depending on what I change about I either get:

 

The website cannot display the page or a list of undefinable variables.

 

If anyone is able to understand the php and notice where the problem lies I would be so grateful.

 

 

Thank you.

 

 

Link to comment
Share on other sites

I believe your error message is coming from the Mail class you are using.  There's a lot more code in your second code example.  I would start small and ONLY use what the Mail class requires to send the email.  Take out the validation and the like and start there.  Strip it down.  Start by passing the values without the Mailer functions.  For example:  Echo the form values after you have submitted the form and see of you are getting those passed okay.  Then move to your Mail operation.  Once you get that working then move to your validation and the like.

 

Comment out ALL your code in form-mailer2.php and add the following.  If you don't see any data at all then you have a problem with calling your form-mailer2.php file.

 


<?php

echo 'Your posted values are: ';
echo $_POST['Name'];
echo $_POST['email'];
echo $_POST['comment'];

?>

Link to comment
Share on other sites

Thankyou, I can see that would be most sensible. I have therefore changed the form-mailer.php to only containing your above code, and interestingly it comes up with a Windows page that the page cannot be displayed. I tried with and without being in <body></body> tags, checked the url for where I had uploaded it. Re-changed it, tried in a new file and saved as a different name, but still no joy. Other php pages, including the first one I evidenced first works still. Any thoughts?

 

Many thanks

 

Link to comment
Share on other sites

Hi

 

I'm starting to get somewhere, with an email being sent to the inbox, with the titles of Name: Email: Comments: on different lines however there is no content from the form being completed on the contact form.

I think the problem is the $body line:

 

  	$body = "Name: $Name\n\n
    Email: $Email\n\n
    Comments: $Comments";

 

I have checked with the contact form page and the field names are definitely as written with capitals etc:

<p>Name: <input name="Name" size="30">
<p>E-mail: <input name="Email" size="30"> 
<p><textarea name="Comments" rows="5" cols="40">

 

Although the message is sent - the echo comes back with "Message successfully sent!" but there is also this too:

 

Notice: Undefined variable: Name in /home/***/public_html/form_mailed.php on line 18

 

Notice: Undefined variable: Email in /home/***/public_html/form_mailed.php on line 19

 

Notice: Undefined variable: Comments in /home/***/public_html/form_mailed.php on line 19

 

 

This is the page so far:

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

$path = '/home/***/php';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require('Mail.php');

$from = "Info <info@**.co.uk>";
$to = "Info <info@**.co.uk>";
$subject = "Hi - Test message!";

  	$body = "Name: $Name\n\n
    Email: $Email\n\n
    Comments: $Comments";
              
$host = "mail.**.co.uk";
$username = "info@**.co.uk";
$password = "***";

$headers = array ('From' => $from,
   'To' => $to,
   'Subject' => $subject);
$smtp = Mail::factory('smtp',
   array ('host' => $host,
     'auth' => true,
     'username' => $username,
     'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
   echo("<p>" . $mail->getMessage() . "</p>");
  } else {
   echo("<p>Message successfully sent!</p>");
  }
?>

 

Thank you again, for your help and looking at this for me. It has given me the glimmer of hope I had almost lost.

 

Louise

Link to comment
Share on other sites

Your are most welcome.  In your code.  I notice

 

    $body = "Name: $Name\n\n
    Email: $Email\n\n
    Comments: $Comments"

 

Where are $Name, $Email, and $Comments getting set?  I believe that's where the error is happening.  They this and see what happens.

 

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

$path = '/home/***/php';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

// Set the email variables from the form here:

    $Name = $_POST['Name']; // Pass the Name value to the $Name variable
    $Email = $_POST['Email']; // Pass the Email value to the $Email variable
    $Comment = $_POST['Comment']; // Pass the Comment value to the $Comment variable

require('Mail.php');

$from = "Info <info@**.co.uk>";
$to = "Info <info@**.co.uk>";
$subject = "Hi - Test message!";

  	$body = "Name: $Name\n\n
            Email: $Email\n\n
            Comments: $Comments";

$host = "mail.**.co.uk";
$username = "info@**.co.uk";
$password = "***";

$headers = array('From' => $from,
                  'To' => $to,
                  'Subject' => $subject);
$smtp = Mail::factory('smtp',
                       array('host' => $host,
                            'auth' => true,
                            'username' => $username,
                            'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
     echo("<p>" . $mail->getMessage() . "</p>");
} else {
     echo("<p>Message successfully sent!</p>");
}
?>


 

 

 

Link to comment
Share on other sites

Because you have error checking set in your code.  Any PHP errors (like "Undefined variable") will be displayed.  If you were to comment those two lines out, you would most likely not have seen those errors.  It's a nice thing sometimes to be able to debug using the below two lines of code in PHP.  However, sometimes those two lines of code could create error messages that you may not care about.

 

        error_reporting(E_ALL);
ini_set('display_errors', True);

 

Happy Coding!!

 

Link to comment
Share on other sites

  • 2 months later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.