PDA

View Full Version : PHP Email Script


Tjobbe
August 16th, 2007, 12:35
I am modifying a standard email script, and I'm stuck.

What I need is a form that a member of staff picks their name from on the drop down list, types in the clients email address, and then depending on the staff name, sends a customised message to the client.

For example: IF name selected = Jane, then send the following message in the body of the email:

"<p>Thanks for your email, Jane is dealing with your query, her email is jane@....com</p>"

OR

IF name selected = Pete, then send the following message in the body of the email:

"<p>Thanks for your email, Pete is dealing with your query, her email is pete@....com</p>".

Here is the form I am using:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
dl {margin:0; padding:0; text-align:left; }
dt {margin:0 0 10px 0; padding:0; width:130px; float:left; text-align:left; }
dd {margin:0 0 10px 150px; padding:0; }
form input {width:310px; }
form {background:#FFFFDD; padding:10px; border:1px solid #E8EAE3; margin:20px; width:480px; }
p .submit {background:#CCCCCC; width:80px; }
.centerAlign{text-align:center; }
</style>
</head>

<body>
<form action="thanks.php" method="post" name="form" id="form">
<dl>
<dt><label for="xname">Your Name</label></dt>
<dd>
<select name="Name" id="xname">
<option>Anne</option>
<option>Jane</option>
<option>Tracy</option>
<option>Pete</option>
</select>
</dd>
<dt><label for="xemail">Clients Email*</label></dt>
<dd><input type="text" id="xemail" name="Email" value="" /></dd>
</dl>
<p class="centerAlign"><input class="submit" type="submit" name="submit" value="Submit" />
<input type="reset" class="submit" name="Reset" value="Clear Form" />
<input type="hidden" name="config" value="0" /></p>
</form>
</body>
</html>

Here is the php script;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<?php
// General Variables
$check_referrer="no";
$referring_domains="http://sitecreative.net/,http://www.sitecreative.net/";

// Default Error and Success Page Variables
$error_page_title="Error - Missed Fields";
$error_page_text="Please use your browser's back button to return to the form and complete the required fields.";
$thanks_page_title="Message Sent";
$thanks_page_text="Thank you for your inquiry, your message has been sent!";

// options to use if hidden field "config" has a value of 0
// recipient info
$charset[0]="iso-8859-1";
$tomail[0]="info@sitecreative.net";
$cc_tomail[0]="";
$bcc_tomail[0]="";
// Mail contents config
$subject[0]="Email from The Bag N Box Man";
$reply_to_field[0]="Email";
$reply_to_name[0]="Name";
$required_fields[0]="Name";
$required_email_fields[0]="Email";
$attachment_fields[0]="";
$return_ip[0]="yes";
$mail_intro[0]="The following is an email from The Bag N Box Man:";
$mail_fields[0]="Name,Email,Phone,Comments";
$mail_type[0]="text";
$mail_priority[0]="1";
// Send back to sender config
$send_copy[0]="no";
$send_copy_format[0]="vert_table";
$send_copy_fields[0]="Name,Comments";
$send_copy_attachment_fields[0]="";
$copy_subject[0]="Subject of Copy Email";
$copy_intro[0]="Thanks for your inquiry, the following message has been delivered.";
$copy_from_email[0]="";
$copy_from_name[0]="";
$copy_tomail_field[0]="Email";
// Result options
$header[0]="";
$footer[0]="";
$error_page[0]="";
$thanks_page[0]="";

// options to use if hidden field "config" has a value of 1
// recipient info
$charset[1]="";
$tomail[1]="";
$cc_tomail[1]="";
$bcc_tomail[1]="";
// Mail contents config
$subject[1]="";
$reply_to_field[1]="";
$reply_to_name[1]="";
$required_fields[1]="";
$required_email_fields[1]="";
$attachment_fields[1]="";
$return_ip[1]="";
$mail_intro[1]="";
$mail_fields[1]="";
$mail_type[1]="";
$mail_priority[1]="";
// Send back to sender config
$send_copy[1]="";
$send_copy_format[1]="";
$send_copy_fields[1]="";
$send_copy_attachment_fields[1]="";
$copy_subject[1]="";
$copy_intro[1]="";
$copy_from_email[1]="";
$copy_from_name[1]="";
$copy_tomail_field[1]="";
// Result options
$header[1]="";
$footer[1]="";
$error_page[1]="";
$thanks_page[1]="";

/////////////////////////////////////////////////////////////////////////
// Don't muck around past this line unless you know what you are doing //
/////////////////////////////////////////////////////////////////////////

ob_start();
$config=$_POST["config"];
$debug=0;

// email validation regular expression
$email_regex = "^[-a-z0-9!#$%&\'*+/=?^_`{|}~]+(\.[-a-z0-9!#$%&\'*+/=?^_`{|}~]+)*@(([a-z]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+([a-z]([-a-z0-9]*[a-z0-9]+)?){2,63}$";
$header_injection_regex = "(\r|\n)(to:|from:|cc:|bcc:)";
if($header[$config]!="")
include($header[$config]);
if($_POST["submit"] || $_POST["Submit"] || $_POST["submit_x"] || $_POST["Submit_x"])
{

////////////////////////////
// begin global functions //
////////////////////////////
// get visitor IP
function getIP()
{
if(getenv(HTTP_X_FORWARDED_FOR))
$user_ip=getenv("HTTP_X_FORWARDED_FOR");
else
$user_ip=getenv("REMOTE_ADDR");
return $user_ip;
}
// get value of given key
function parseArray($key)
{
$array_value=$_POST[$key];
$count=1;
extract($array_value);
foreach($array_value as $part_value)
{
if($count > 1){$value.=", ";}
$value.=$part_value;
$count=$count+1;
}
return $value;
}
// stripslashes and autolink url's
function parseValue($value)
{
$value=preg_replace("/(http:\/\/+.[^\s]+)/i",'<a href="\\1">\\1</a>', $value);
return $value;
}
// html header if used
function htmlHeader()
{
$htmlHeader="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n<html>\n<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=".$charset[$config]."\"></head>\n<body>\n<table cellpadding=\"2\" cellspacing=\"0\" border=\"0\" width=\"600\">\n";
return $htmlHeader;
}
// html footer if used
function htmlFooter()
{
$htmlFooter="</table>\n</body>\n</html>\n";
return $htmlFooter;
}
// build verticle table format
function buildVertTable($fields, $intro, $to, $send_ip)
{
$message=htmlHeader();
if($intro != "")
$message.="<tr>\n<td align=\"left\" valign=\"top\" colspan=\"2\">".$intro."</td>\n</tr>\n";
$fields_check=preg_split('/,/',$fields);
$run=sizeof($fields_check);
for($i=0;
$i<$run;
$i++)
{
$cur_key=$fields_check[$i];
$cur_value=$_POST[$cur_key];
if(is_array($cur_value))
{
$cur_value=parseArray($cur_key);
}
$cur_value=parseValue($cur_value);
$message.="<tr>\n<td align=\"left\" valign=\"top\" style=\"white-space:nowrap;\"><b>".$cur_key."</b></td>\n<td align=\"left\" valign=\"top\" width=\"100%\">".nl2br($cur_value)."</td>\n</tr>\n";
}
if($send_ip=="yes" && $to=="recipient")
{
$user_ip=getIP();
$message.="<tr>\n<td align=\"left\" valign=\"top\" style=\"white-space:nowrap;\"><b>Sender IP</b></td>\n<td align=\"left\" valign=\"top\" width=\"100%\">".$user_ip."</td>\n</tr>\n";
}
$message.=htmlFooter();
return $message;
}
// build horizontal table format
function buildHorzTable($fields, $intro, $to, $send_ip)
{
$message=htmlHeader();
$fields_check=preg_split('/,/',$fields);
$run=sizeof($fields_check);
if($intro != "")
$message.="<tr>\n<td align=\"left\" valign=\"top\" colspan=\"".$run."\">".$intro."</td>\n</tr>\n";
$message.="<tr>\n";
for($i=0;
$i<$run;
$i++)
{
$cur_key=$fields_check[$i];
$message.="<td align=\"left\" valign=\"top\" style=\"white-space:nowrap;\"><b>".$cur_key."</b></td>\n";
}
if($send_ip=="yes" && $to=="recipient")
$message.="<td align=\"left\" valign=\"top\" style=\"white-space:nowrap;\"><b>Sender IP</b></td>\n";
$message.="</tr>\n";
$message.="<tr>\n";
for($i=0;
$i<$run;
$i++)
{
$cur_key=$fields_check[$i];
$cur_value=$_POST[$cur_key];
if(is_array($cur_value))
{
$cur_value=parseArray($cur_key);
}
$cur_value=parseValue($cur_value);
$message.="<td align=\"left\" valign=\"top\">".nl2br($cur_value)."</td>\n";
}
$message.="</tr>\n";
$message.="<tr>\n";
if($send_ip=="yes" && $to=="recipient")
{
$user_ip=getIP();
$message.="<td align=\"left\" valign=\"top\">".$user_ip."</td>\n";
}
$message.="</tr>\n";
$message.=htmlFooter();
return $message;
}
// build plain text format
function buildTextTable($fields, $intro, $to, $send_ip)
{
$message="";
if($intro != "")
$message.=$intro."\n\n";
$fields_check=preg_split('/,/',$fields);
$run=sizeof($fields_check);

for($i=0;
$i<$run;
$i++)

{

$cur_key=$fields_check[$i];
$cur_value=$_POST[$cur_key];

if(is_array($cur_value))

{

$cur_value=parseArray($cur_key);

}

$cur_value=parseValue($cur_value);
$message.="".$cur_key.": ".$cur_value."\n\n";

}

if($send_ip=="yes" && $to=="recipient")

{

$user_ip=getIP();
$message.="Sender IP: ".$user_ip."\n";

}

return $message;

}

// get the proper build fonction

function buildTable($format, $fields, $intro, $to, $send_ip)

{

if($format=="vert_table")

$message=buildVertTable($fields, $intro, $to, $send_ip);

else if($format=="horz_table")

$message=buildHorzTable($fields, $intro, $to, $send_ip);

else

$message=buildTextTable($fields, $intro, $to, $send_ip);

return $message;

}

// referrer checking security option

function checkReferer()

{

if($check_referrer=="yes")

{

$ref_check=preg_split('/,/',$referring_domains);
$ref_run=sizeof($ref_check);
$referer=$_SERVER['HTTP_REFERER'];
$domain_chk="no";

for($i=0;
$i<$ref_run;
$i++)

{

$cur_domain=$ref_check[$i];

if(stristr($referer,$cur_domain)){$domain_chk="yes";}

}

}

else

{

$domain_chk="yes";

}

return $domain_chk;

}

// checking required fields and email fields

function checkFields($text_fields, $email_fields, $email_regex)

{

$error_message="";

if($debug==1)

$error_message.="<li>text_fields: ".$text_fields."<br />email_fields: ".$email_fields."<br />reply_to_field: ".$reply_to_field[$config]."<br />reply_to_name: ".$reply_to_name[$config]."</li>";

if($text_fields != "")

{

$req_check=preg_split('/,/',$text_fields);
$req_run=sizeof($req_check);

for($i=0;
$i<$req_run;
$i++)




I would like to know where I would put the IF statements to tell the script what message to email to the client?

(I had to chop the php into two pieces - message length was too long, rest is in message below:)

I just can't seem to figure that bit out!

Tjobbe
August 16th, 2007, 12:35
{

$cur_field_name=$req_check[$i];
$cur_field=$_POST[$cur_field_name];

if($cur_field=="")

{

$error_message.="<li>You are missing the <b>".$req_check[$i]."</b> field</li>\n";

}

}

}

if($email_fields != "")

{

$email_check=preg_split('/,/',$email_fields);
$email_run=sizeof($email_check);

for($i=0;
$i<$email_run;
$i++)

{

$cur_email_name=$email_check[$i];
$cur_email=$_POST[$cur_email_name];

if($cur_email=="" || !eregi($email_regex, $cur_email))

{

$error_message.="<li>You are missing the <b>".$email_check[$i]."</b> field or it is not a valid email address.</li>\n";

}

}

}

return $error_message;

}

// attachment function

function getAttachments($attachment_fields, $message, $content_type, $border)

{

$att_message="This is a multi-part message in MIME format.\n\n";
$att_message.="--{$border}\n";
$att_message.=$content_type."\n";
$att_message.="Content-Transfer-Encoding: 7bit\n\n";
$att_message.=$message."\n\n";
$att_check=preg_split('/,/',$attachment_fields);
$att_run=sizeof($att_check);

for($i=0;
$i<$att_run;
$i++)

{

$fileatt=$_FILES[$att_check[$i]]['tmp_name'];
$fileatt_name=$_FILES[$att_check[$i]]['name'];
$fileatt_type=$_FILES[$att_check[$i]]['type'];

if (is_uploaded_file($fileatt))

{

$file=fopen($fileatt,'rb');
$data=fread($file,filesize($fileatt));

fclose($file);
$data=chunk_split(base64_encode($data));
$att_message.="--{$border}\n";
$att_message.="Content-Type: {$fileatt_type}; name=\"{$fileatt_name}\"\n";
$att_message.="Content-Disposition: attachment; filename=\"{$fileatt_name}\"\n";
$att_message.="Content-Transfer-Encoding: base64\n\n".$data."\n\n";

}

}

$att_message.="--{$border}--\n";

return $att_message;

}

// function to set content type

function contentType($charset, $format)

{

if($format=="vert_table")

$content_type="Content-type: text/html; charset=\"".$charset."\"\n";

else if($format=="horz_table")

$content_type="Content-type: text/html; charset=\"".$charset."\"\n";

else

$content_type="Content-type: text/plain; charset=\"".$charset."\"\n";

return $content_type;

}

// header injection filter

function headerInjectionFilter($reply_to_field, $reply_to_name, $header_injection_regex)

{

$security_filter="";

if(strlen($reply_to_field) > 0)

{

if(eregi($header_injection_regex,$reply_to_field))

$security_filter.="<li>Header injection attempt detected in 'email' data, mail aborted.</li>\n";

if(eregi($header_injection_regex,$reply_to_name))



$security_filter.="<li>Header injection attempt detected in 'name' data, mail aborted.</li>\n";

}

return $security_filter;

}

//////////////////////////

// end global functions //

//////////////////////////



////////////////////////////////

// begin procedural scripting //

////////////////////////////////

$domain_chk=checkReferer();

if($domain_chk=="yes")

{

$security_filter=headerInjectionFilter($_POST[$reply_to_field[$config]], $_POST[$reply_to_name[$config]], $header_injection_regex);
$error_message=checkFields($required_fields[$config], $required_email_fields[$config], $email_regex);

if(strlen($error_message) < 1 && strlen($security_filter) < 1)

{

// build appropriate message format for recipient

$content_type=contentType($charset[$config], $mail_type[$config]);
$message=buildTable($mail_type[$config], $mail_fields[$config], $mail_intro[$config], "recipient", $return_ip[$config]);

// build header data for recipient message

$extra="From: ".$_POST[$reply_to_name[$config]]." <".$_POST[$reply_to_field[$config]].">\n";

if($cc_tomail[$config]!="")


$extra.="Cc: ".$cc_tomail[$config]."\n";

if($bcc_tomail[$config]!="")

$extra.="Bcc: ".$bcc_tomail[$config]."\n";
$extra.="X-Priority: ".$mail_priority[$config]."\n";

// get attachments if necessary

if($attachment_fields[$config]!="")

{

$semi_rand=md5(time());
$border="==Multipart_Boundary_x{$semi_rand}x";
$extra.="MIME-Version: 1.0\n";
$extra.="Content-Type: multipart/mixed; boundary=\"{$border}\"";
$message=getAttachments($attachment_fields[$config], $message, $content_type, $border);

}

else

{

$extra.="MIME-Version: 1.0\n".$content_type;

}

// send recipient email

if($debug==1)

echo "<p><strong>Mail would have sent if not in <em>debug mode</em></strong>.</p>";

else if($debug==0)

mail("".$tomail[$config]."", "".stripslashes($subject[$config])."", "".stripslashes($message)."", "$extra");

// autoresponse email if necessary

if($send_copy[$config]=="yes")

{

// build appropriate message format for autoresponse

$content_type=contentType($charset[$config], $send_copy_format[$config]);
$message=buildTable($send_copy_format[$config], $send_copy_fields[$config], $copy_intro[$config], "autoresponder", $return_ip[$config]);

// build header data for autoresponse

$copy_extra="From: ".$copy_from_name[$config]." <".$copy_from_email[$config].">\n";

// get autoresponse attachments if necessary

if($send_copy_attachment_fields[$config]!="")

{

$semi_rand=md5(time());
$border="==Multipart_Boundary_x{$semi_rand}x";
$copy_extra.="MIME-Version: 1.0\n";
$copy_extra.="Content-Type: multipart/mixed; boundary=\"{$border}\"";
$message=getAttachments($send_copy_attachment_fiel ds[$config], $message, $content_type, $border);

}

else

{

$copy_extra.="MIME-Version: 1.0\n".$content_type;

}

// send autoresponse email

$send_copy = 1;

if($_POST[$copy_tomail_field[$config]]=="" || !eregi($email_regex,$_POST[$copy_tomail_field[$config]]))


$send_copy = 0;

if($send_copy == 1 && $debug==1)

echo "<p><strong>Autoresponder would have sent if not in <em>debug mode</em></strong>.</p>";

else if($send_copy == 1 && $debug==0)

mail("".$_POST[$copy_tomail_field[$config]]."", "".$copy_subject[$config]."", "$message", "$copy_extra");

else if($send_copy==0)

echo "<p>Email malformed, autoreponse not sent.</p>";

}

// showing thanks pages from a successful submission

if($thanks_page[$config]=="")

{

echo "<h1>$thanks_page_title</h1>\n";

echo "<p>$thanks_page_text</p>\n";

}

else

{

header("Location: ".$thanks_page[$config]);

}

}

else

{

// entering error page options from missing required fields

if($error_page[$config]=="")

{

echo "<h1 style='color:red'>$error_page_title</h1>\n";

echo "<ul>\n";

echo $security_filter;

echo $error_message;

echo "</ul>\n";

echo "<p>$error_page_text</p>\n";

}

else

{

header("Location: ".$error_page[$config]);

}

}

}

else

{

// message if unauthorized domain trigger from referer checking option

echo "<p>Sorry, mailing request came from an unauthorized domain.</p>\n";

}

//////////////////////////////

// end procedural scripting //

//////////////////////////////



}

else

{

echo "<p>Error</p>";

echo "<p>No form data has been sent to the script</p>\n";

}

if($footer[$config]!="")

include($footer[$config]);

ob_end_flush();

?>

</body>
</html>

inimino
August 21st, 2007, 02:10
I would like to know where I would put the IF statements to tell the script what message to email to the client?

First search for "mail(", as the mail() function is typically used to send emails from PHP.

You'll find this:

mail("".$tomail[$config]."", "".stripslashes($subject[$config])."", "".stripslashes($message)."", "$extra");

And if you look up the mail() function in the PHP documentation you can read what each argument is for. The third argument is the body of the email, so next you'd need to search for the $message variable to see where it's assigned. There's a bunch of $message.="..." statements which build an ugly HTML table, and you'd need to modify one of those to add what you want to add.

However, the other thing I notice about that mail() call is that the first argument, specifying the address to send the mail to, comes from the configuration at the top of the script, so if you're trying to send email to an arbitrary address this script may not be what you want.

Tjobbe
August 21st, 2007, 10:40
First search for "mail(", as the mail() function is typically used to send emails from PHP.

You'll find this:

mail("".$tomail[$config]."", "".stripslashes($subject[$config])."", "".stripslashes($message)."", "$extra");

And if you look up the mail() function in the PHP documentation you can read what each argument is for. The third argument is the body of the email, so next you'd need to search for the $message variable to see where it's assigned. There's a bunch of $message.="..." statements which build an ugly HTML table, and you'd need to modify one of those to add what you want to add.

However, the other thing I notice about that mail() call is that the first argument, specifying the address to send the mail to, comes from the configuration at the top of the script, so if you're trying to send email to an arbitrary address this script may not be what you want.

Thanks Mj,

Makes perfect sense, but which one of the $message variables do I modify? Which one is going to make a difference? The sent email does not contain any tables so I'm wondering why they are in there.

I added the following to the script, at various points but it didn't change the email body:


if ($email=="Jane")
{
$message="This is a message from Jane";
}

if ($email=="Pete")
{
$message="This is a message from Pete";
}

if ($email=="Anne")
{
$message="This is a message from Anne";
}



What's the obvious thing that I'm doing wrong?

inimino
August 21st, 2007, 10:45
There's only one $message variable, it's just built by appending strings to it (that's what the .= operator does). You really don't want to be using if statements at all here, just add something like: $message .= "This is a message from $email";

Tjobbe
August 21st, 2007, 11:01
There's only one $message variable, it's just built by appending strings to it (that's what the .= operator does). You really don't want to be using if statements at all here, just add something like: $message .= "This is a message from $email";

ah I understand, thanks.

I'm still struggling I have to say - sorry. I have tried adding the above in the script as a standalone or by replacing an existing $message variable to no joy. What should I be looking for? The current email body is this:

The following is an email from The Bag N Box Man:

Name: Anne

Email: tjobbe@gmail.com

Phone:

Comments:

inimino
August 21st, 2007, 11:11
Add that line immediately above the "mail(..." line, and you should see a difference in the email that is sent, specifically it will append "This is a message from" and the value of the variable $email to the message.

What you should be looking for is every occurrence of "$message" in the entire script until you can see how the message is constructed.

Tjobbe
August 21st, 2007, 11:44
there does not appear to be a predefined $email variable anywhere in the script, I added: $email="Name"; near the top but that then showed "this is an email from Name" in the body, then I changed that to $email="$name"; which didn't display anything.

I then changed that to $email="$reply_to_name"; which showed "This is an email from Array", which I just don't understand!

I can't figure out where to get the name from..

Tjobbe
August 21st, 2007, 12:15
I'm sure you have probably gone to bed by now - don't blame you!

If you do still have some patience left, I need to figure out how to set the recipient depending on the name selected from the drop down box on the form, and what message to send depending on the name selected.

inimino
August 22nd, 2007, 00:01
there does not appear to be a predefined $email variable anywhere in the script

That's because you added it to the form yourself, if I understood your original post correctly.

I can't figure out where to get the name from..

Like any HTML form variable in PHP, use either $_POST or $_GET. In this case, $_POST['Name'] will contain the value from the <select>. Check the PHP documentation on handling form submission for the details.

Incidentally, if you use both a name and id attribute on any element, they must have the same value (this requirement is in HTML 4.01). It makes DOM programming simpler as well as you don't have to remember two different unique values that both refer to the same thing. So fix your <select> to look something like <select name="name" id="name">.