I have a website that uses php mailer to send form input to a phone using the Verizon service. The issue is that the online form is being sent to a phone via text using the PHP mailer.
On the Android phones, the email is received properly and displayed in its entirety as a text message.
On an iPhone, the email is received as a text message, but it's truncated and only a portion is displayed. Notice that it stops at 'Cu.' It supposed to have about eight more lines of information pertaining to the appointment schedule. I'm wondering if iPhone has a character limit shorter than Android phones.
Anyone know how to avoid the text from being truncated on the iPhone?
I've googled for information, but all I get is how to fix the native iPhone email client. Which, isn't the issue.
Thank you.
It's pretty straight forward. The code pulls the form variables and assigns them as variable variables to the $message variable in a foreach loop.
<pre>
if ($OK_customers && $OK_appointments && $OK_customers_appointment) {
$message = '';
$selected_appt_day = date('l', strtotime($appt_date));
$selected_appt_date = date('m-d-Y', strtotime($appt_date));
$message .= "\r\n: ".$selected_appt_day.", ".$selected_appt_date."\r\n\r\n";
$message .= "Please confirm:\r\n\r\n";
foreach ($expected as $item) {
if (isset(${$item}) && !empty(${$item})) {
$val = ${$item};
}else {
$val = 'Not Selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(['_', '-'], ' ', $item);
$message .= ucfirst($item) . ": $val\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
</pre>
Related
I have a strange issue. My SaaS receives leads from various third party companies via email (I know ... its old school). I use the pipe to a program feature in cpanel to send the email to a script that parses out the to from subject and message. In the message is a xml message. Here is the code for this (php):
$lines = explode("\n", $email_content);
// initialize variable which will assigned later on
$from = "";
$subject = "";
$headers = "";
$message = "";
$is_header= true;
//loop through each line
for ($i=0; $i < count($lines); $i++) {
if ($is_header) {
// hear information. instead of main message body, all other information are here.
$headers .= $lines[$i]."\n";
// Split out the subject portion
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
//Split out the sender information portion
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
} else {
// content/main message body information
//$message .= $lines[$i]."\n";
$message .= $lines[$i];
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$is_header = false;
}
}
Then I just insert the variables into my MySQL database. For some of the emails this works perfect. But some emails the xml gets odd characters inserted. An example below
<?xml version=3D"1.0" encoding=3D"UTF-8"?>=0D=0A<?adf version=3D"1.0"?>==0D=0A<adf>
Notice the '3D' and '=0D=0A' .... I believe this may have to do with the encoding? Some are UTF 8, UTF 16 and the ones that work do not have a UTF assigned.
I am inserting the xml part into a 'TEXT' type as MySQL does not seem to have a XML option.
Okay so basically i have this subscription input where people enter their email and click a button... Once they click the button the company email gets notified of the new subscriber (it receives a email and in the email states the email the user inputted)... anyways i've got it working so it does that and also writes whatever the user inputted into a .txt file.. Its all working but after i successfully got it to write to the text file, the success text after clicking the subscribe button dosent show...
HTML:
<div class="span12 subscribe">
<h3>Subscribe to our newsletter</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" action="assets/sendmail.php" method="post">
<input type="text" name="email" placeholder="Enter your email...">
<button type="submit" class="btn">Subscribe</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
</div>
PHP:
<?php
// Email address verification
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'subscriptions#servready.com';
$subscriber_email = ($_POST['email']);
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thanks for your subscription!';
echo json_encode($array);
// Send email
$subject = 'New Subscriber!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
$headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body, $headers);
}
$data = $_POST['email']."\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
?>
If i remove this part of the php script, the success and invalid email text pops up:
$data = $_POST['email']."\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
Like i said, its functional, but the success text or invalid email errors and success texts don't pop up with the code that writes the persons emails to the text file.
Site is http://servready.com for testing
Per the comments above, it is the content being echoed out after echo json_encode -- the extra content breaks the JSON echoed out causing everything else to break.
http://servready.com/assets/js/scripts.js is the JS file with your countdown time in it -- it's hardcoded into the script, so that's why it starts over. You'd need to put some code in there to determine the appropriate time for the countdown to reflect. I sugget you give that a try and then post a followup question with any issues you may need assistance with.
Glad to help!
I have a mysql database table called "leads" with an id column, a name column, and an email column. I currently have users selecting a lead from a multiple select box, which is returned as an array from an html form with $_POST method. I have the value for the select box items as the email column, and what is shown to the user on the front end is the name column. However, I want to be able to return two values, the email and the name, for later use. I need to have the email value(s) able to be imploded with commas between them, so I can later send them emails using PHP's mail function. However, when a user looks at sent emails, I want to show them the name value(s). I have read that I can either parse the array, or use the id column set as the value, which seems more practical, however, I am not sure how I would go about this. Any ideas? Thanks in advance for any help!
*UPDATE*
Basically, the users that log into the site have their own leads in a mysql database. I need them to be able to go to a 'send email' page, where they can select a lead, or multiple leads, by name. Then there is a subject field, and a message field so they can write the email, and then I have a 'send email' form submit button. After they click 'send email' I want to get back the email addresses and names of the leads they selected, for later use. I need to have the email addresses separated by commas, so that I can send them through a php mail function... But the important thing is, I want the info from the form to be stored in a database table called 'PendingEmails', and I am going to run a cron job to run a script that finds what emails need to be sent, and sends them... After an email is sent, I need to put the names, subject, and message from the email in a separate database, called 'SentEmails'. On a different page on the site, I want the users to be able to see all the emails they sent, but I want them to see the names of who they sent it to, rather than the email addresses. This is why I need both the names and the emails. I need emails for the mail function, and names to be displayed back to the user. I like your idea of using the id and running the rest server side, I just dont know how I would do this. Hope this helped.
Here is the select box:
<select data-placeholder="Select Lead(s) To Email..." multiple="true" class="chzn-container-multi" name="selectleads[]"style="width:505px;">
<?php
do {
?>
<option value="<?php echo $row_rsAllLeads['Email']?>"><?php echo $row_rsAllLeads['FullName']?></option>
<?php
} while ($row_rsAllLeads = mysql_fetch_assoc($rsAllLeads));
$rows = mysql_num_rows($rsAllLeads);
if($rows > 0) {
mysql_data_seek($rsAllLeads, 0);
$row_rsAllLeads = mysql_fetch_assoc($rsAllLeads);
}
?>
</select>
And here is the actual form action:
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form")) {
$startcode = $_POST['messagefield'];
$replaced = preg_replace( '/\\\\(?="|\')/', '', $startcode );
$selected = $_POST['selectleads'];
$collectedleads = implode(", ", $_POST['selectleads']);
$to = $collectedleads;
$subject = $_POST['subjectfield'];
$body = $replaced;
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: " . $row_rs_CurrentUser['FirstName'] . " " . $row_rs_CurrentUser['LastName'] . " <" . $row_rs_CurrentUser['Email'] . ">";
if (mail($to, $subject, $body, $headers)) {
} else {
echo("<p>Message delivery failed...</p>");
}
}
The code you gave me and I tried (and failed) to edit and make work:
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form")) {
$startcode = $_POST['messagefield'];
$replaced = preg_replace( '/\\\\(?="|\')/', '', $startcode );
mysql_select_db($database_myBackOfficeConn, $myBackOfficeConn);
$collectedleads = implode(", ", $_POST['selectleads']);
//arrays to store email addresses and names
$emails = array();
$names = array();
foreach ($collectedleads as $id) {
mysql_query("SELECT Email, FullName FROM Leads
WHERE Id = " . mysql_real_escape_string($id));
while ($row = mysql_fetch_assoc()) {
$emails[] = $row['Email'];
$names[] = $row['FullName'];
}
}
$to = $collectedleads;
$subject = $_POST['subjectfield'];
$body = $replaced;
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: " . $row_rs_CurrentUser['FirstName'] . " " . $row_rs_CurrentUser['LastName'] . " <" . $row_rs_CurrentUser['Email'] . ">";
if (mail($to, $subject, $body, $headers)) {
} else {
echo("<p>Message delivery failed...</p>");
}
}
?>
I think it would make more sense to do the retrieving of data on the server-side. Instead of the email addresses, set the <option> values to your database's id column values.
EDIT: Changed most of the answer after discussing with OP
Bearing in mind that the code you posted was just a snippet, and so I have no way of testing this, you could try something along these lines:
<select data-placeholder="Select Lead(s) To Email..." multiple="true"
class="chzn-container-multi" name="selectleads[]"style="width:505px;">
<?php
/* I think while is better, in case there are no results.
do...while would attempt to echo the first result in a set even
if there were no results, which would give an error, methinks. */
//Use the id field of your database when you populate the select
while ($row_rsAllLeads = mysql_fetch_assoc($rsAllLeads)) { ?>
<option value="<?php echo $row_rsAllLeads['id']?>">
<?php echo $row_rsAllLeads['FullName']?></option>
<?php
}
/* What is this block used for? */
$rows = mysql_num_rows($rsAllLeads);
if($rows > 0) {
mysql_data_seek($rsAllLeads, 0);
$row_rsAllLeads = mysql_fetch_assoc($rsAllLeads);
}
?>
</select>
I'm uncertain as to the purpose of the code block at the end so I just left it. I assume you do something else with that data...?
So now your <select> is exactly the same as before, but instead of actual email addresses it will hand back the corresponding database ids instead.
Now, on submitting the data, we change our tack slightly:
<?php
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form")) {
$startcode = $_POST['messagefield'];
$replaced = preg_replace( '/\\\\(?="|\')/', '', $startcode );
$selected = $_POST['selectleads'];
/* NEW CODE */
/*selectleads[] is now an array of your database's ids.
You can now run a query to get whatever information you
need. In this case, you want the email addresses, so:
*/
$collectedleads = $_POST['selectleads'];
$emailaddylist = array();
foreach ($collectedleads as $id) {
$x = mysql_query("SELECT `Email` FROM `leads` WHERE `id` = " .
mysql_real_escape_string($id));
$x_assoc = $x->fetch_assoc();
$emailaddylist[] = $x['Email'];
}
/*Now you have an array of email addresses that correspond to
the ids you were sent via $_POST.
*/
$emailaddystring = implode(", ", $emailaddylist);
$to = $emailaddystring;
/*If you want to use any other data from the database,
you still have an array of ids in $collectedleads.
Just run another query to get the data you want.*/
/* END OF NEW CODE */
$subject = $_POST['subjectfield'];
$body = $replaced;
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: " . $row_rs_CurrentUser['FirstName'] . " " . $row_rs_CurrentUser['LastName'] . " <" . $row_rs_CurrentUser['Email'] . ">";
if (mail($to, $subject, $body, $headers)) {
} else {
echo("<p>Message delivery failed...</p>");
}
}
?>
Because we are handed the ids in an array, we can use them to get whatever information we want from the database. In this case we're just getting the email addresses. If you want to retrieve any other information, you can use the same technique - the list of ids still exists in $collectedleads, so you can run another query to get whatever data you need.
After an email is sent, I need to put the names, subject, and message
from the email in a separate database, called 'SentEmails'
In that case, use the id data in $collectedleads to run a SELECT query on leads to get the information you need (name, email address, whatever), and run an INSERT query on the SentEmails table to copy that information.
Hope this helps.
CAVEAT:
The use of mysql is discouraged in favour of mysqli. To quote the page:
If you are using MySQL versions 4.1.3 or later it is strongly
recommended that you use the mysqli extension instead.
It works almost exactly the same; in most cases all you need to do is to put the i in front of it. Some functions don't work with it, or have better alternatives. You should check it out.
What I would do, I would add a hidden field named something along the lines of "lead_name" and fill it with jQuery or just plain JS on an onblur event with the value of the selected lead.
$("#lead_name").val($("#lead option:selected").text());
I'm trying to send an e-mail to multiple e-mail address in my database. Here is my current code. It is only working when I specify a single e-mail address, however, I need to have them query my database and send the e-mail to each e-mail address. Where am I going wrong here?
$elist = $database->getRows("SELECT * FROM `emails`");
if ($elist) {
foreach ($elist as $elist_result) {
$frm = 'rdsyh#gmail.com';
$sub = 'Weekly Work Report';
ob_start(); // start output buffering
include_once('mail_content.php');
$mail_body = ob_get_contents(); // get the contents from the buffer
ob_end_clean();
$to = $elist_result['email'];
$mailstatus = l_mail('', '', $to, $elist_result['firstname'] . ' ' . $elist_result['lastname'], $frm, 'HR', $sub, $mail_body);
}
}
if ($mailstatus == 'ok') {
echo '<center><font color=red style="font-size:14px">Message has been sent Succesfully.....!</font></center><br>';
} else {
echo $mailstatus;
}
Well, there's a lot of abstraction here that we know nothing about from your code. Things to check:
Are you certain that your database query is returning all of the results you're looking for (is $elist populated properly)?
Are you certain that the query is returning data in the format that you're trying to access it in (is $to populated properly)?
Are you certain your l_mail() function is behaving (is it possible it exit's or otherwise terminates script execution in the middle of the first pass)?
Based on what I see here, if everything else was working properly, you should successfully be sending a bunch of emails, one to each email in your list.
Now, if instead you're trying to send a single email that is sent to all of the addresses at once, then you need to group the email addresses in the for loop and then run your mail function afterwards:
<?
$tos = array();
foreach ($elist as $elist_result) {
$tos[] = $elist_result['email'];
}
$frm = 'rdsyh#gmail.com';
$sub = 'Weekly Work Report';
ob_start(); // start output buffering
include_once('mail_content.php');
$mail_body = ob_get_contents(); // get the contents from the buffer
ob_end_clean();
$to = implode(', ', $tos);
$mailstatus = l_mail('', '', $to, $elist_result['firstname'] . ' ' . $elist_result['lastname'], $frm, 'HR', $sub, $mail_body);
?>
What does l_mail() do? If its a web service, then it might have limit for mass emails.
Problem: Blank email from PHP web application.
Confirmed: App works in Linux, has various problems in Windows server environment. Blank emails are the last remaining problem.
PHP Version 5.2.6 on the server
I'm a librarian implementing a PHP based web application to help students complete their assignments.I have installed this application before on a Linux based free web host and had no problems.
Email is controlled by two files, email_functions.php and email.php. While email can be sent, all that is sent is a blank email.
My IT department is an ASP only shop, so I can get little to no help there. I also cannot install additional libraries like PHPmail or Swiftmailer.
You can see a functional copy at http://rpc.elm4you.org/ You can also download a copy from Sourceforge from the link there.
Thanks in advance for any insight into this!
email_functions.php
<?php
/**********************************************************
Function: build_multipart_headers
***********************************************************
Purpose:
Creates email headers for a message of type multipart/mime
This will include a plain text part and HTML.
**********************************************************/
function build_multipart_headers($boundary_rand)
{
global $EMAIL_FROM_DISPLAY_NAME, $EMAIL_FROM_ADDRESS, $CALC_PATH, $CALC_TITLE, $SERVER_NAME;
// Using \n instead of \r\n because qmail doubles up the \r and screws everything up!
$crlf = "\n";
$message_date = date("r");
// Construct headers for multipart/mixed MIME email. It will have a plain text and HTML part
$headers = "X-Calc-Name: $CALC_TITLE" . $crlf;
$headers .= "X-Calc-Url: http://{$SERVER_NAME}/{$CALC_PATH}" . $crlf;
$headers .= "MIME-Version: 1.0" . $crlf;
$headers .= "Content-type: multipart/alternative;" . $crlf;
$headers .= " boundary=__$boundary_rand" . $crlf;
$headers .= "From: $EMAIL_FROM_DISPLAY_NAME <$EMAIL_FROM_ADDRESS>" . $crlf;
$headers .= "Sender: $EMAIL_FROM_DISPLAY_NAME <$EMAIL_FROM_ADDRESS>" . $crlf;
$headers .= "Reply-to: $EMAIL_FROM_DISPLAY_NAME <$EMAIL_FROM_ADDRESS>" . $crlf;
$headers .= "Return-Path: $EMAIL_FROM_DISPLAY_NAME <$EMAIL_FROM_ADDRESS>" . $crlf;
$headers .= "Date: $message_date" . $crlf;
$headers .= "Message-Id: $boundary_rand#$SERVER_NAME" . $crlf;
return $headers;
}
/**********************************************************
Function: build_multipart_body
***********************************************************
Purpose:
Builds the email body content to go with the headers from
build_multipart_headers()
**********************************************************/
function build_multipart_body($plain_text_message, $html_message, $boundary_rand)
{
//$crlf = "\r\n";
$crlf = "\n";
$boundary = "__" . $boundary_rand;
// Begin constructing the MIME multipart message
$multipart_message = "This is a multipart message in MIME format." . $crlf . $crlf;
$multipart_message .= "--{$boundary}{$crlf}Content-type: text/plain; charset=\"us-ascii\"{$crlf}Content-Transfer-Encoding: 7bit{$crlf}{$crlf}";
$multipart_message .= $plain_text_message . $crlf . $crlf;
$multipart_message .= "--{$boundary}{$crlf}Content-type: text/html; charset=\"iso-8859-1\"{$crlf}Content-Transfer-Encoding: 7bit{$crlf}{$crlf}";
$multipart_message .= $html_message . $crlf . $crlf;
$multipart_message .= "--{$boundary}--$crlf$crlf";
return $multipart_message;
}
/**********************************************************
Function: build_step_email_body_text
***********************************************************
Purpose:
Returns a plain text version of the email body to be used
for individually sent step reminders
**********************************************************/
function build_step_email_body_text($stepnum, $arr_instructions, $dates, $query_string, $teacher_info ,$name, $class, $project_id)
{
global $CALC_PATH, $CALC_TITLE, $SERVER_NAME;
$step_email_body =<<<BODY
$CALC_TITLE
Step $stepnum: {$arr_instructions["step$stepnum"]["title"]}
Name: $name
Class: $class
BODY;
$step_email_body .= build_text_single_step($stepnum, $arr_instructions, $dates, $query_string, $teacher_info);
$step_email_body .= "\n\n";
$step_email_body .=<<<FOOTER
The $CALC_TITLE offers suggestions, but be sure to check with your teacher to find out the best working schedule for your assignment!
If you would like to stop receiving further reminders for this project, click the link below:
http://$SERVER_NAME/$CALC_PATH/deleteproject.php?proj=$project_id
FOOTER;
// Wrap text to 78 chars per line
// Convert any remaining HTML <br /> to \r\n
// Strip out any remaining HTML tags.
$step_email_body = strip_tags(linebreaks_html2text(wordwrap($step_email_body, 78, "\n")));
return $step_email_body;
}
/**********************************************************
Function: build_step_email_body_html
***********************************************************
Purpose:
Same as above, but with HTML
**********************************************************/
function build_step_email_body_html($stepnum, $arr_instructions, $dates, $query_string, $teacher_info, $name, $class, $project_id)
{
global $CALC_PATH, $CALC_TITLE, $SERVER_NAME;
$styles = build_html_styles();
$step_email_body =<<<BODY
<html>
<head>
<title> $CALC_TITLE </title>
$styles
</head>
<body>
<h1> $CALC_TITLE Schedule </h1>
<strong>Name:</strong> $name <br />
<strong>Class:</strong> $class <br />
BODY;
$step_email_body .= build_html_single_step($stepnum, $arr_instructions, $dates, $query_string, $teacher_info);
$step_email_body .=<<<FOOTER
<p>
The $CALC_TITLE offers suggestions, but be sure to check with your teacher to find out the best working schedule for your assignment!
</p>
<p>
If you would like to stop receiving further reminders for this project,
click this link.
</p>
</body>
</html>
FOOTER;
return $step_email_body;
}
/**********************************************************
Function: build_html_styles
***********************************************************
Purpose:
Just returns a string of <style /> for the HTML message body
**********************************************************/
function build_html_styles()
{
$styles =<<<STYLES
<style type="text/css">
body { font-family: Arial, sans-serif; font-size: 85%; }
h1 { font-size: 120%; }
table { border: none; }
tr { vertical-align: top; }
img { display: none; }
hr { border: 0; }
</style>
STYLES;
return $styles;
}
/**********************************************************
Function: linebreaks_html2text
***********************************************************
Purpose:
Convert <br /> html tags to \n line breaks
**********************************************************/
function linebreaks_html2text($in_string)
{
$out_string = "";
$arr_br = array("<br>", "<br />", "<br/>");
$out_string = str_replace($arr_br, "\n", $in_string);
return $out_string;
}
?>
email.php
<?php
require_once("include/config.php");
require_once("include/instructions.php");
require_once("dbase/dbfunctions.php");
require_once("include/email_functions.php");
ini_set("sendmail_from", "reference#cna-qatar.edu.qa");
ini_set("SMTP", "mail.qatar.net.qa");
// Verify that the email has not already been sent by checking for a cookie
// whose value is generated each time the form is loaded freshly.
if (!(isset($_COOKIE['rpc_transid']) && $_COOKIE['rpc_transid'] == $_POST['transid']))
{
// Setup some preliminary variables for email.
// The scanning of $_POST['email']already took place when this file was included...
$to = $_POST['email'];
$subject = $EMAIL_SUBJECT;
$boundary_rand = md5(rand());
$mail_type = "";
switch ($_POST['reminder-type'])
{
case "progressive":
$arr_dbase_dates = array();
$conn = rpc_connect();
if (!$conn)
{
$mail_success = FALSE;
$mail_status_message = "Could not register address!";
break;
}
// Sanitize all the data that will be inserted into table...
// We need to remove "CONTENT-TYPE:" from name/class to defang them.
// Additionall, we can't allow any line-breaks in those fields to avoid
// hacks to email headers.
$ins_name = mysql_real_escape_string($name);
$ins_name = eregi_replace("CONTENT-TYPE", "...Content_Type...", $ins_name);
$ins_name = str_replace("\n", "", $ins_name);
$ins_class = mysql_real_escape_string($class);
$ins_class = eregi_replace("CONTENT-TYPE", "...Content_Type...", $ins_class);
$ins_class = str_replace("\n", "", $ins_class);
$ins_email = mysql_real_escape_string($email);
$ins_teacher_info = $teacher_info ? "YES" : "NO";
switch ($format)
{
case "Slides": $ins_format = "SLIDES"; break;
case "Video": $ins_format = "VIDEO"; break;
case "Essay":
default: $ins_format = "ESSAY"; break;
}
// The transid from the previous form will be used as a project identifier
// Steps will be grouped by project identifier.
$ins_project_id = mysql_real_escape_string($_POST['transid'] . md5(rand()));
$arr_dbase_dates = dbase_dates($dates);
$arr_past_dates = array();
// Iterate over the dates array and build a SQL statement for each one.
$insert_success = TRUE;
//
$min_reminder_date = date("Ymd", mktime(0,0,0,date("m"),date("d")+$EMAIL_REMINDER_DAYS_AHEAD,date("Y")));
for ($date_index = 0; $date_index < sizeof($arr_dbase_dates); $date_index++)
{
// Make sure we're using the right keys...
$ins_date_index = $date_index + 1;
// The insert will only happen if the date of the event is in the future.
// For dates today and earlier, no insert.
// For dates today or after the reminder deadline, we'll send the email immediately after the inserts.
if ($arr_dbase_dates[$date_index] > (int)$min_reminder_date)
{
$qry =<<<QRY
INSERT INTO email_queue
(
NOTIFICATION_ID,
PROJECT_ID,
EMAIL,
NAME,
CLASS,
FORMAT,
TEACHER_INFO,
STEP,
MESSAGE_DATE
)
VALUES (
NULL,
'$ins_project_id',
'$ins_email',
'$ins_name',
'$ins_class',
'$ins_format',
'$ins_teacher_info',
$ins_date_index, /*step number*/
{$arr_dbase_dates[$date_index]} /* Date in the integer format yyyymmdd */
)
QRY;
// Attempt to do the insert...
$result = mysql_query($qry);
// If even one insert fails, bail out.
if (!$result)
{
$mail_success = FALSE;
$mail_status_message = "Could not register address!";
break;
}
}
// For dates today or earlier, store the steps=>dates in an array so the mails can
// be sent immediately.
else
{
$arr_past_dates[$ins_date_index] = $arr_dbase_dates[$date_index];
}
}
// Close the connection resources.
mysql_close($conn);
// SEND OUT THE EMAILS THAT HAVE TO GO IMMEDIATELY...
// This should only be step 1, but who knows...
//var_dump($arr_past_dates);
for ($stepnum=1; $stepnum<=sizeof($arr_past_dates); $stepnum++)
{
$email_teacher_info = ($teacher_info && $EMAIL_TEACHER_REMINDERS) ? TRUE : FALSE;
$boundary = md5(rand());
$plain_text_body = build_step_email_body_text($stepnum, $arr_instructions, $dates, $query_string, $email_teacher_info ,$name, $class, $ins_project_id);
$html_body = build_step_email_body_html($stepnum, $arr_instructions, $dates, $query_string, $email_teacher_info ,$name, $class, $ins_project_id);
$multipart_headers = build_multipart_headers($boundary);
$multipart_body = build_multipart_body($plain_text_body, $html_body, $boundary);
mail($to, $subject . ": Step " . $stepnum, $multipart_body, $multipart_headers, "-fresearch#rpc.elm4you.org");
}
// Set appropriate flags and messages
$mail_success = TRUE;
$mail_status_message = "Email address registered!";
$mail_type = "progressive";
set_mail_success_cookie();
break;
// Default to a single email message.
case "single":
default:
// We don't want to send images in the message, so strip them out of the existing structure.
// This big ugly regex strips the whole table cell containing the image out of the table.
// Must find a better solution...
//$email_table_html = eregi_replace("<td class=\"stepImageContainer\" width=\"161px\">[\s\r\n\t]*<img class=\"stepImage\" src=\"images/[_a-zA-Z0-9]*\.gif\" alt=\"Step [1-9]{1} logo\" />[\s\r\n\t]*</td>", "\n", $table_html);
// Show more descriptive text based on the value of $format
switch ($format)
{
case "Video": $format_display = "Video"; break;
case "Slides": $format_display = "Presentation with electronic slides"; break;
case "Essay":
default:
$format_display = "Essay"; break;
}
$days = (int)$days;
$html_message = "";
$styles = build_html_styles();
$html_message =<<<HTMLMESSAGE
<html>
<head>
<title> $CALC_TITLE </title>
$styles
</head>
<body>
<h1> $CALC_TITLE Schedule </h1>
<strong>Name:</strong> $name <br />
<strong>Class:</strong> $class <br />
<strong>Email:</strong> $email <br />
<strong>Assignment type:</strong> $format_display <br /><br />
<strong>Starting on:</strong> $date1 <br />
<strong>Assignment due:</strong> $date2 <br />
<strong>You have $days days to finish.</strong><br />
<hr />
$email_table_html
</body>
</html>
HTMLMESSAGE;
// Create the plain text version of the message...
$plain_text_message = strip_tags(linebreaks_html2text(build_text_all_steps($arr_instructions, $dates, $query_string, $teacher_info)));
// Add the title, since it doesn't get built in by build_text_all_steps...
$plain_text_message = $CALC_TITLE . " Schedule\n\n" . $plain_text_message;
$plain_text_message = wordwrap($plain_text_message, 78, "\n");
$multipart_headers = build_multipart_headers($boundary_rand);
$multipart_message = build_multipart_body($plain_text_message, $html_message, $boundary_rand);
$mail_success = FALSE;
if (mail($to, $subject, $multipart_message, $multipart_headers, "-reference#cna-qatar.edu.qa"))
{
$mail_success = TRUE;
$mail_status_message = "Email sent!";
$mail_type = "single";
set_mail_success_cookie();
}
else
{
$mail_success = FALSE;
$mail_status_message = "Could not send email!";
}
break;
}
}
function set_mail_success_cookie()
{
// Prevent the mail from being resent on page reload. Set a timestamp cookie.
// Expires in 24 hours.
setcookie("rpc_transid", $_POST['transid'], time() + 86400);
}
?>
Instead of sending it, build the email and display all of the vars used in the mail call to the screen and comment out the mail call. That will confirm that the vars are being properly constructed.
Then start using the mail function again, if you have access to mail logs that would help as well, as it may give you more information. Also, take a look at the headers on the email you receive as that also may show you that a header or 2 is messed up.
Also try setting $crlf = "\r\n";
brett, if you think it's the headers, i'd try the bare minimum and get it to work. once it works, start adding headers until you get the error. then let us know what the problem is.