Need help with PHP script using PHPMailer.


#1

Hello to anybody that is reviewing this thread.

I’m not a big time PHP expert, and really just trying to execute some PHP script in a contact form provided to me by easy PHP (which uses PHPMailer) on my webpage. This form is for someone to contact me. I do not reply back through the website as I use Outlook with Exchange Server 2007 on a 2008 box using IIS7.

I went with PHPMailer because the “mail()” function doesn’t seem to be working at all or I’m just not configuring the PHP.ini file correctly. As a matter of fact, it was working just fine until I started getting a validation email error: Mailer Error: The following From address failed: un@domain.com. This is a verified email address as I use it ALL the time. I can receive and send emails to any email I wish using my Exchange email account.

The PHP.ini file is set as
SMTP = mail.mydomain.com
SMTP_port = 25
SMTP_from = my user name.

I’ve tried sending mail with a test email script; with localhost with port 25 as the php.ini settings and keep getting the common mail function error: Failed to connect to mailserver at mydomain.com port 25, verify your SMTP and SMTP_port setting in php.ini file is correct. Those are set correctly. I have made sure my port is set up correctly in my router. Simple enough.

Hear is the easy PHP code using PHPMailer “contact-form.php”

[php]
$body = “$name[0]: $name[2]\r\n\r\n”;
$body .= “$email[0]: $email[2]\r\n\r\n”;
$body .= “$message[0]:\r\n$message[2]\r\n\r\n”;

if (!$from) $from_value = $email[2];
else $from_value = $from;

require_once('formfiles/class.phpmailer.php');

$mail = new PHPMailer(); 

$mail->IsSMTP();
$mail->SMTPAuth = $smtp_auth;
$mail->Host = $smtp_host;
$mail->Port = $smtp_port;
$mail->Username = $smtp_username;
$mail->Password = $smtp_password; 
$mail->SetFrom($from_value);  
$mail->AddReplyTo($email[2]);
$mail->Subject = "$subject_prefix - $subject[2]";
$mail->Body = $body;
$mail->AddAddress($to);

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
}[/php]

This is the output script that creates the form for you when you use the [php]<?php include "contact-form.php"; ?>[/php] statement. It creates a simple HTML table that calls each variable in the contact-form.php script.

[code]

{$email[4]}[/code]

This creates the FROM field; the person simply puts in their email address and fills out the rest of the required fields.

What I still don’t “get” is why do I have to worry about setting up SMTP anyways? The are contacting me from my website and not going through a relay SMTP server.

Any help would be MUCH appreciated in tackling this.

Thank you


#2

You shouldn’t need to use the SMTP info. It will use the server’s version. You do need headers to be able to send an email. Here is sample code that I use to send emails and it has worked well. It does not match your code, it is just a sample for you to review. Hope it helps…
[php]
//(first validate if these are here and valid…)
$email_to = “me.myserver.com”;
$email_copy = $_POST[‘copy_address’];
$email_from = $_POST[‘email_address’];
$email_subject = $_POST[‘email_subject’];
$email_message = $_POST[‘message’];
$email_message = “This email sent from the ‘my site…’ website.\r\n\r\n”; //text send to me…
$email_message .= “Whatever text to send from the contact-us page…\r\n\r\n”;
$current_month = date(“F”);
$current_date = date(“d”);
$current_year = date(“Y”);
$current_time = date(“H:i”);
$timestamp = strtotime($month . " " . $date . " " . $year . " " . $time);
$email_message .= "Email was sent on " . $current_month . " " . $current_date . ", " . $current_year . " at " . $current_time;

// create email headers
$headers = 'From: ' . $email_from . "\r\n" . 'Reply-To: ' . $email_from . "\r\n" . 'CC: ' . $email_copy . "\r\n" . 'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

// after email is sent, do a pop-up alert to say so...  then go back to contacts page...
header("Location: YourmailSent.php");

[/php]
Just a sample of my version, might help fix up yours…


#3

Hello Ernie, thanks so much for the quick response and new code.

Just another questions, will I be able to implement the new code provided by you into the php script that I downloaded from EasyPHP? They do have a non SMTP script with CAPTCHA but it still calls the mail() handler. When I use that one it throws an error at me stating it couldn’t initiate the mail function?

Or am I just going to have to build a new HTML form that fits those variables?

I know this is long, but I’ve included the PHP code from the non SMTP version. The script also builds the form for you… Just wondering if I could take the script provided by you and somehow tweak it in this one… If not, could you provide me with a link to a good tutorial to build my own form page where I can customize the name, email, subject and message body to my liking. I have a page background that is blackish white.
Thanks again for you help!

[php]
require “formfiles/contact-config.php”;

$error_message = ‘’;

if (!isset($_POST[‘submit’])) {

showForm();

} else { //form submitted

$error = 0;

if(!empty($_POST[‘name’])) {
$name[2] = clean_var($_POST[‘name’]);
}
else {
$error = 1;
$name[3] = ‘color:#FF0000;’;
}

if(!empty($_POST[‘email’])) {
$email[2] = clean_var($_POST[‘email’]);
if (!validEmail($email[2])) {
$error = 1;
$email[3] = ‘color:#FF0000;’;
$email[4] = ‘Invalid email’;
}
}
else {
$error = 1;
$email[3] = ‘color:#FF0000;’;
}

if(!empty($_POST[‘subject’])) {
$subject[2] = clean_var($_POST[‘subject’]);
if (function_exists(‘htmlspecialchars’)) $subject[2] = htmlspecialchars($subject[2], ENT_QUOTES);
}
else {
$error = 1;
$subject[3] = ‘color:#FF0000;’;
}

if(!empty($_POST[‘message’])) {
$message[2] = clean_var($_POST[‘message’]);
if (function_exists(‘htmlspecialchars’)) $message[2] = htmlspecialchars($message[2], ENT_QUOTES);
}
else {
$error = 1;
$message[3] = ‘color:#FF0000;’;
}

if(empty($_POST[‘captcha_code’])) {
$error = 1;
$code[3] = ‘color:#FF0000;’;
} else {
include_once “formfiles/contact-securimage.php”;
$securimage = new Securimage();
$valid = $securimage->check($_POST[‘captcha_code’]);

if(!$valid) {
  $error = 1;
  $code[3] = 'color:#FF0000;';   
  $code[4] = '<strong><span style="color:#FF0000;">Incorrect code</span></strong>';
}

}

if ($error == 1) {
$error_message = ‘

Please correct/enter field(s) in red.
’;
showForm();

} else {

if (function_exists('htmlspecialchars_decode')) $subject[2] = htmlspecialchars_decode($subject[2], ENT_QUOTES);
if (function_exists('htmlspecialchars_decode')) $message[2] = htmlspecialchars_decode($message[2], ENT_QUOTES);  	

$body = "$name[0]: $name[2]\r\n\r\n";
$body .= "$email[0]: $email[2]\r\n\r\n";
$body .= "$message[0]:\r\n$message[2]\r\n\r\n";

if (!$from) $from_value = $email[2];
else $from_value = $from;

require_once('formfiles/class.phpmailer.php');

$mail = new PHPMailer();

$mail->SetFrom($from_value);  
$mail->AddReplyTo($email[2]);
$mail->Subject = "$subject_prefix - $subject[2]";
$mail->Body = $body;
$mail->AddAddress($to);

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
}

if (!$thank_you_url) {    
  if ($use_header_footer) include $header_file;
  echo '<a name="cform"><!--Form--></a>'."\n";
  echo '<div id="formContainer" style="width:'.$form_width.';height:'.$form_height.';text-align:left; vertical-align:top;">'."\n";
  echo $GLOBALS['thank_you_message']."\n";
  echo '</div>'."\n";
  if ($use_header_footer) include $footer_file;
  }
  else {
  	header("Location: $thank_you_url");
  }
  
  session_unset();
session_destroy();	  

}

} //else submitted

function showForm()

{
global $name, $email, $subject, $message, $code;
global $where_included, $use_header_footer, $header_file, $footer_file;
global $form_width, $form_height, $form_background, $form_border_color, $form_border_width, $form_border_style, $cell_padding, $left_col_width;

if ($use_header_footer) include $header_file;

echo <<<EOD

{$GLOBALS['error_message']}
{$name[0]}
{$email[0]} {$email[4]}
{$subject[0]}
{$message[0]} {$message[2]}
  CAPTCHA Image
{$code[0]} {$code[4]}

(Please enter the text in the image above. Text is not case sensitive.)
Click here if you cannot recognize the code.
All fields are required.
EOD;

if ($use_header_footer) include $footer_file;
}

function clean_var($variable) {
$variable = strip_tags(stripslashes(trim(rtrim($variable))));
return $variable;
}

/**
Email validation function. Thanks to http://www.linuxjournal.com/article/9585
/
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, “@”);
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == ‘.’ || $local[$localLen-1] == ‘.’)
{
// local part starts or ends with ‘.’
$isValid = false;
}
else if (preg_match(’/\.\./’, $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match(’/^[A-Za-z0-9\-\.]+$/’, $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match(’/\.\./’, $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if (!preg_match(’/^(\\.|[A-Za-z0-9!#%&`_=\/$’
+?^{}|~.-])+$/’, str_replace("\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match(’/^"(\\"|[^"])+"$/’,
str_replace("\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && function_exists(‘checkdnsrr’))
{
if (!(checkdnsrr($domain,“MX”) || checkdnsrr($domain,“A”))) {
// domain not found in DNS
$isValid = false;
}
}
}
return $isValid;
}

?>[/php]


#4

Well, first, you are using EasyPHP which is a product. It is sort of a CMS system for a backend of your PHP server. I do not know this system and so far, most people I talk to are using the XAMPP system from APACHE. If you want to learn FORM’s, HTML and PHP, you will find all you want for tutorials thru Google.
Here is one to start you off…

http://www.tizag.com/htmlT/forms.php

It covers most of the general input fields, radio button, etc. And, how to access the data users input to you. Then, you can use my code to send the data by email. Should get you started… Good luck…