I have this mailing list from php mailer examples: https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps
so I put the foreach loop within a while loop so it iterates through the entire table, I'm using a token array to replace the name and any dynamic content, the content is working, but it keeps putting the wrong name in the email.
The name and email are inserted into vac_mailing_system table correctly. but when it's selected it seems to grab a random name and assign it to a random email address. So this makes me think there is an issue with the select statement.
$finish_table = $dbh->prepare("SELECT * FROM vac_mailing_system WHERE sent_status = false AND retry_attempts < 5");
if($finish_table->execute()) {
$finish_table->setFetchMode(PDO::FETCH_ASSOC);
}
while($row = $finish_table->fetch()) {
$vac_id = $row['vac_id'];
$vac_name = $row['vac_name'];
$vac_comp = $row['vac_comp'];
$full_name = $row['full_name'];
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = '';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = ;
$mail->Username = '';
$mail->Password = '';
$mail->setFrom('', 'Information');
$mail->addReplyTo('', ' Information');
$mail->Subject = "Information";
$mail->Body = strtr(file_get_contents('new_vac_email.html'), array('%full_name%' => $full_name, '%vac_id%' => $vac_id, '%vac_name%' => $vac_name, '%vac_comp%' => $vac_comp));
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
//msgHTML also sets AltBody, but if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
//Connect to the database and select the recipients from your mailing list that have not yet been sent to
//You'll need to alter this to match your database
$mysql = mysqli_connect('host', 'user', 'pass');
mysqli_select_db($mysql, 'db_name');
$result = mysqli_query($mysql, "SELECT * FROM vac_mailing_system WHERE sent_status = false AND retry_attempts < 5 LIMIT 0, 50");
foreach ($result as $row) { //This iterator syntax only works in PHP 5.4+
$mail->addAddress($row['email_address'], $full_name);
if (!$mail->send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email_address"]) . ') ' . $mail->ErrorInfo . '<br />';
//Mark it as sent in the DB
mysqli_query(
$mysql,
"UPDATE vac_mailing_system SET sent_status = false, retry_attempts = +1 WHERE email_address = '" .
mysqli_real_escape_string($mysql, $row['email_address']) . "'"
);
break; //Abandon sending
} else {
echo "Message sent to :" . $full_name . ' (' . str_replace("#", "#", $row['email_address']) . ')<br />';
//Mark it as sent in the DB
mysqli_query(
$mysql,
"UPDATE vac_mailing_system SET sent_status = true WHERE email_address = '" .
mysqli_real_escape_string($mysql, $full_name) . "'"
);
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
$mail->clearAttachments();
}
sleep(60);
echo "emails sent";
}
Try this code:
Yes, very easily with include and a short helper function:
function get_include_contents($filename, $variablesToMakeLocal) {
extract($variablesToMakeLocal);
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "You have an event today";
$mail->Body = get_include_contents('new_vac_email.php', $data); // HTML -> PHP!
$mail->Send(); // send message
Try this code:
// first we will create small helper function
function get_include_contents($filename, $variablesToMakeLocal) {
extract($variablesToMakeLocal);
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "You have an event today";
// rename your new_vac_email.html file to your new_vac_email.php
// create a data array which contains replace values
// here user_name is variable name in new_vac_email.php
//Adarsh hatkar is value which is shown in place of <?php echo ($user_name); ?>
$data = array('user_name' => 'Adarsh hatkar' );
$mail->Body = get_include_contents('new_vac_email.php', $data);
$mail->Send(); // send message
demo new_vac_email.php file code for example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Email Confirmation</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body >
<p>Hello <?php echo ($user_name); ?> </P>
</body>
</html>
Related
I need assistance with sending bulk email.
This is this scanario.
A dropdown contains the categories of emails to be fetched. The selected (value) is then passed through a function that obtains all the emails per the selected value from db. And the emails passed to the mailer's addAddress method.
The sql query works fine but my headers show only the selected value from the network session and not all the returned emails. I am including both php codes and the ajax codes and also the response headers.
PHP block
$accountid = $_POST['accountid'];
$selectedstatus = $_POST['bulkrecipients']; //From dropdown
$emailtype = $_POST['emailtype'];
$subject = sanitize_text($_POST['bulksubject']);
$message = sanitize_text($_POST['bulkmessage']);
//Pass recipientemails to function and extract individual emails.
$getemails = getAllEmailsFromStatus($selectedstatus , $_SESSION['username']);
$name = 'Tester';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPKeepAlive = true;
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = "";
$mail->Password = '';
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
$mail->isHTML(true);
$mail->setFrom('testproject222', $name);
$mail->Subject = ("$subject");
$mail->Body = $message;
foreach ($getemails as $row) {
try {
$mail->addAddress($row['email']);
} catch (Exception $ex) {
echo 'Invalid address skipped: ' . htmlspecialchars($row['email']) . '<br>';
continue;
}
try {
if ($mail->send()) {
$status = "success";
$response = "Email is sent";
//Save the contact details to db.
saveAllEmployerEmails($accountid , $subject, emailtype, $message );
} else {
$status = "failed";
$response = 'Something is wrong ' . $mail->ErrorInfo;
}
exit(json_encode(array("status" => $status, "response" => $response)));
} catch (Exception $ex) {
echo 'Mailer Error (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
$mail->getSMTPInstance()->reset();
}
$mail->clearAddresses();
$mail->clearAttachments();
}
Ajax
function sendBulk() {
var url = "./inc/emailjobs.php";
var accountid = $("#accountid");
var emailtype = $("#emailtype");
var recipientemails = $("#bulkrecipients");
var bulksubject = $("#bulksubject");
var bulkmessage = $('#' + 'bulkmessage').html( tinymce.get('bulkmessage').getContent() );
if (isNotEmpty(recipientemails) /*&& isNotEmptyTextArea("bulkmessage")*/) {
$.ajax({
url: url,
method: 'POST',
cache: false,
dataType: 'json',
beforeSend: function () {
$('#bulksendbtn').text("Sending...");
},
data: {
accountid: accountid.val(),
emailtype: emailtype.val(),
bulksubject: bulksubject.val(),
bulkrecipients: recipientemails.val(),
bulkmessage: bulkmessage.val()
}
, success: function (response) {
$('#bulkemailForm')[0].reset();
$('.bulksendmessage').text("Emails Sent.");
$('#bulksendbtn').text("Sent");
},
});
}
}
Response Form header data
accountid: 2
emailtype: bulk
bulksubject: Test
bulkrecipients: shortlisted
bulkmessage: <p>Testing... </p>
Instead of the 'shortlisted' for bulkrecipients, I expect the email addresses. I was hoping to see 2 returned emails. The 'shortlisted' is supposed to be used to obtain the emails for that category (shortlisted).
Your code looks generally correct, but this is confusing:
$mail->setFrom('Test', $name);
//$mail->From = ("$email");
$email isn't defined, and Test is not a valid from address. I have a suspicion you're trying to use an arbitrary user-submitted email address as the from address. That will not work with Gmail because Gmail does not allow setting arbitrary from addresses; it will only let you send as the account owner (what you put in Username), or aliases that you preset in gmail settings. If you try to use anything else, it will simply ignore it and use your account address instead. Is this what you meant by "only the selected value from the network session"?
It's entirely reasonable for gmail to do this since almost by definition anything other than your account address is likely to be forgery, and nobody likes that.
If you want to send email where replies will go to a user-submitted address, use your own address in the from address, and use the user-submitted address as a reply-to. See the contact form example provided with PHPMailer for how to do that.
In below code, we are first selecting users based on the admin's input from database. Then sending emails to those users. With the code it sends emails to $mail_news->addAddress('testuser#gmail.com'); test user. But for the bcc part is not working, as it doesn't send any emails to bcc email users.
foreach($email_array as $news_mail){
$mail_news->AddBCC($news_mail.";");
}
This is how we fetch user emails via form & PHP prepare statement with mysqli.
Here is the main part code:
if($msn->execute()){
$msn->store_result();
$msn->bind_result($news_mail);
while($msn->fetch()){
$email_array[] = $news_mail;
}
// echo "successful";
}
else
{
echo "database failed";
}
//--Email Sending Starts
$mail_news = new PHPMailer;
$mail_news->isSMTP();
$mail_news->Host = EMAIL_HOST;
$mail_news->SMTPAuth = true;
$mail_news->Port = EMAIL_PORT;
$mail_news->SMTPSecure = 'tls';
$mail_news->Username = EMAIL_ADD;
$mail_news->Password = EMAIL_PASS;
$mail_news->From = EMAIL_ADD;
$mail_news->FromName = 'Company Account';
$mail_news->addAddress('testuser#gmail.com');
foreach($email_array as $news_mail){
$mail_news->AddBCC($news_mail.";");
}
$mail_news->WordWrap = 50;
// $mail_news->SMTPDebug = 2;
$mail_news->isHTML(true);
$mail_news->Subject = "".$sub;
$mail_news->Body = "".$body;
$mail_news->AltBody = "".$altbody;
if(!$mail_news->send()) {
echo "Failed Sending Emails" ;
echo 'Mailer Error: ' . $mail_news->ErrorInfo;
} else {
echo "All Email sending completed" ;
}
?>
</form>
<?php
$msn->close(); // Finally closing the database
}
?>
You need to change the line
$mail_news->AddBCC($news_mail.";");
with
$mail_news->AddBCC($news_mail);
because the method addBCC() handles the semicolon by itself. You do not need to specify by your own.
Here is my problem,
I have a PHPmailer object that works fine in the file "enviar1.php",but when I serialize this object,store it in a session variable and try to unserialize and use it in another file,it doesnt work.the issue is that the email is sent,but with no subject,no body and no attachments.
File:"enviar1.php"
[...]
$email = new PHPMailer();
$email->CharSet = 'UTF-8';
$emaildes = "";
$campusEsc = addslashes($campus);
$query = "SELECT email FROM bibliotecarios WHERE campus = '$campusEsc'";
$emailBibliotecario = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($emailBibliotecario))
$emaildes = $row['email'];
$email->isSMTP();
$email->Host ="ssl://smtp.googlemail.com";
$email->SMTPAuth = true;
$email->Port = 465;
$email->Username = "someemail";
$email->Password = "somepass";
$email->From = "someemail";
$email->FromName = "Sistema de Encaminhamento de Ficha";
$email->AddAddress($emaildes, "bibliotecario do campus " . $campus);
$email->IsHTML(true);
$email->Subject = "ficha catalografica para revisao";
$mensagem = "<p>ficha do(a) aluno(a):" . $nome . " " . $sobrenome . "(" .$emailAluno . ") do campus de " . $campus . "</p>" ;
$mensagem .= "</br>";
$mensagem .= "</br>";
$email->Body = $mensagem;
$email->AddStringAttachment($string, 'ficha Catalografica - ' . $nome . " " . $sobrenome . '.odt');
$email->AddStringAttachment($string2, 'ficha Catalografica - ' . $nome . " " . $sobrenome . '.docx');
$email->AddAttachment($_FILES["arquivo"]["tmp_name"],$_FILES["arquivo"]["name"] );
session_start();
$_SESSION['nome'] = $nome; //I need these variables to create TBS a object in "preview.php"
$_SESSION['sobrenome'] = $sobrenome;
$_SESSION['email'] = $emailAluno;
$_SESSION['titulo'] = $titulo;
$_SESSION['subtitulo'] = $subtitulo;
$_SESSION['ano'] = $ano;
$_SESSION['folhas'] = $folhas;
$_SESSION['ilus'] = $ilus;
$_SESSION['tipo'] = $tipo;
$_SESSION['curso'] = $curso;
$_SESSION['campus'] = $campus;
$_SESSION['orientacao'] = $orientacao;
$_SESSION['coorientacao'] = $coorientacao;
$_SESSION['assunto1'] = $assunto1;
$_SESSION['assunto2'] = $assunto2;
$_SESSION['assunto3'] = $assunto3;
$_SESSION['assunto4'] = $assunto4;
$_SESSION['assunto5'] = $assunto5;
if($autorizacao != "true") //this is a checkbox from the previus form
{
if ($email->Send()) //here the email works like a charm
header("Location: preview.php");
else
echo "Erro ao enviar o email";
}
else
{
$_SESSION['emailParcial'] = serialize($email); //I stored in a session variable to edit the object later
header("Location: termo.php");//just another page with a form
}
[...]
the problem is in this file "enviar2.php",the email is sent to the correct destiny but empty,no subject,no body and none attachments.
file:"Enviar2.php"
<?php
ini_set("display_errors", true);
error_reporting(-1);
require 'configuracoes.php';
include_once('tbs_class.php');
include_once('tbs_plugin_opentbs.php');
function __autoload( $className ) {
require_once('./phpmailer/class.phpmailer.php');
}
[...]
$emailcompleto = new PHPMailer();
session_start();
$emailcompleto = unserialize($_SESSION['emailParcial']);
echo $emailcompleto->Body; //I put this to test the value and its ok
echo $emailcompleto->Subject; //the value is ok,the same as the $email object from "enviar1.php" file
if ($emailcompleto->Send()) //the email is sent but i get a empty email.
header("Location: preview.php");
else
echo "Erro ao enviar o email" . $email->ErrorInfo;
[...]
I dont know why it is not working,I used a echo and printed the Properties of the $emailcompleto object,they have correct values,it has the same subject and body of the $email object from the "enviar1.php" file has,but in the end i get a empty email.
someone have a clue of what is happening?
doc of class PHPmailer: http://www.tig12.net/downloads/apidocs/wp/wp-includes/PHPMailer.class.html#det_methods_AddAddress
It's easy....
PHPMailer can send a pre-created email if it's separated into Header and Body. PHPMailer can also create a Header and Body separate of each other:
$header = $mailer->createHeader();
$body = $mailer->createBody();
Once you have that data - you can store it in any manner you choose. Calling it up at a later time to send using any of the 3 PHPMailer Send() methods:
// SMTP
$mailer->smtpSend($header,$body);
// Sendmail
$mailer->sendmailSend($header,$body);
// PHP Mail
$mailer->mailSend($header,$body);
I am sending emails using PHPmailer. As of now, I am successful in sending email to one address. Now, I want to send multiple emails in just one click.
PROBLEM: I have tried to use some loops below to send multiple email but I get wrong outpout. Yes, it sends email but to only one address, and the email address is getting all of the emails that are supposed to be emailed to other emails.
For example, when I send 17 emails, those 17 emails are sent to only one address. The emails should be sent according to the addresses in the database, with corresponding unique attachments. Example: abc#gmail.com should have abc.pdf attached, and 123#gmail.com should have 123.pdf attached.
I think it's in the loop. Please help me figure it out. Thanks.
require_once('phpmailer/class.phpmailer.php');
include("phpmailer/class.smtp.php");
$mail = new PHPMailer();
$body = file_get_contents('phpmailer/body.html');
$body = preg_replace('/\/b]/','',$body);
$file ='phpmailer/mailpass.txt';
if($handle = fopen($file,"r")){
$contentpass = fread($handle,'15');
fclose($handle);
}
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = "email#gmail.com";
$mail->Password = $contentpass;
$mail->SetFrom("email#gmail.com", "Subject");
$mail->AddReplyTo("email#gmail.com","Subject");
$mail->Subject = "Subjects";
$mail->AltBody = "Subject";
$mail->MsgHTML($body);
$file='current_schoolyear.txt';
if($handle = fopen($file,"r"))
{
$content = fread($handle,'9');
fclose($handle);
}
$input = addslashes($_POST['depchair']);
$email = "select email_address from sa_student where schoolyear = '$input'";
if ($p_address=mysql_query($email))
{
while($row = mysql_fetch_assoc($p_address))
{
$mail->AddAddress($row['email_address']);
$input = addslashes($_POST['depchair']);
$control = "select control_no from sa_student where schoolyear = '$input'";
if($ctrl=mysql_query($control)){
$ctrl_no = mysql_result($ctrl, 0);
$mail->AddAttachment("fpdf/pdf_reports/document/".$ctrl_no.".pdf");
}
else
{
echo "No attached document.";
}
if(!$mail->Send()) {
$message = "<div class=\"nNote nFailure\" >
<p>Error sending email. " . $mail->ErrorInfo ."</p>
</div>";
} else {
$message = "<div class=\"nNote nSuccess\" >
<p> Email have been sent to the examinees in ".$input_depchair. "! </p>
</div>";
}
}
}
else
{
echo (mysql_error ());
}
UPDATED CODE: After running the code below, I was able to send an email and with the correct attachment. However, there was only ONE email sent (the last email address in the database), and the rest of the emails were not sent.
$input = addslashes($_POST['depchair']);
$email = "select email_address, control_no from sa_student where schoolyear = '$input'";
if ($p_address=mysql_query($email))
{
while($row = mysql_fetch_assoc($p_address))
{
$cloned = clone $mail;
$cloned->AddAddress($row['email_address']);
$cloned->AddAttachment("fpdf/pdf_reports/document/".$row['control_no'].".pdf");
if(!$cloned->Send()) {
$message = "<div class=\"nNote nFailure\" >
<p>Error sending email. " . $mail->ErrorInfo ."</p>
</div>";
} else {
$message = "<div class=\"nNote nSuccess\" >
<p> Email have been sent to the examinees in ".$input_depchair. "! </p>
</div>";
}
unset( $cloned );
}
}
else
{
echo (mysql_error ());
}
After you send an email $mail->Send(), execute this:
$mail->ClearAllRecipients();
in your while loop.
So your basic while loop structure looks like this:
while($row = mysql_fetch_assoc($p_address)){
$mail->AddAddress($row['email_address']);
$mail->AddAttachment("fpdf/pdf_reports/document/".$ctrl_no.".pdf");
$mail->send();
$mail->ClearAllRecipients();
$mail->ClearAttachments(); //Remove all attachements
}
Within your loop, create a clone of the $mail object - before you add the recipient and attachment - then use the clone to send the email. The next loop iteration will create a new clone free of the previous address and attachment:
while($row = mysql_fetch_assoc($p_address)) {
$cloned = clone $mail;
$cloned->AddAddress($row['email_address']);
// add attchment to $cloned, etc.
if ( $cloned->send() ) { /* etc */ }
unset( $cloned );
}
This will "clear" your per-iteration changes (like address, attachment, etc) without you having to reenter config properties (like, from, host, etc.)
Addendum:
Your attachments will likely be all the same because you're not fetching new results for these lines (within your loop):
$input=addslashes($_POST['depchair']);
$control = "select control_no from sa_student where schoolyear = '$input'";
if ($ctrl=mysql_query($control)) {
$ctrl_no = mysql_result($ctrl, 0);
$mail->AddAttachment("fpdf/pdf_reports/document/".$ctrl_no.".pdf");
}
$ctrl_no will always return the same result because (I'm assuming) $_POST['depchair'] does not change - thus $input, $control, $ctrl, and $ctrl_no all remain (effectively) the same for each loop. You need to find whatever it is your actually intend to be the $ctrl_no for each loop - right now you're using the same one over and over.
The following query could probably help:
// replace
// $email = "select email_address from sa_student where schoolyear = '$input'";
// with:
$students_query = "select email_address, control_no from sa_student where schoolyear = '$input'";
// then
// if ($p_address=mysql_query($email)) {
// while($row = mysql_fetch_assoc($p_address)) {
// becomes
if ( $students=mysql_query($students_query) ) {
while ( $row = mysql_fetch_assoc( $students ) ) {
// so that finally, etc
$cloned->AddAddress($row['email_address']);
$ctrl_no = $row['control_no'];
This pulls both the student email address and their control_no in the same query, making sure they stay associated with each other through the loop. You can then get rid of the second mid-loop query, since all the results you need were pulled in the first out-of-loop query. The above isn't all the code you need to change, just the critical parts.
The following program is intended to match incoming email aliases with those in the database, and forward the email to the right address, like Craigslist does.
I am now getting this error:
Error: [1] You must provide at least one recipient email address.
in anon-email.php at line number: sending the email
Here is the code:
$mailboxinfo = imap_mailboxmsginfo($connection);
$messageCount = $mailboxinfo->Nmsgs; //Number of emails in the inbox
for ($MID = 1; $MID <= $messageCount; $MID++)
{
$EmailHeaders = imap_headerinfo($connection, $MID); //Save all of the header information
$Body = imap_qprint(imap_fetchbody($connection, $MID, 1)); //The body of the email to be forwarded
$MessageSentToAllArray = $EmailHeaders->to; //Grab the “TO” header
$MessageSentToAllObject = $MessageSentToAllArray[0];
$MessageSentToMailbox = $MessageSentToAllObject->mailbox ."#". $MessageSentToAllObject->host; //Everything before and after the “#” of the recipient
$MessageSentFromAllArray = $EmailHeaders->from; //Grab the “FROM” header
$MessageSentFromAllObject = $MessageSentFromAllArray[0];
$MessageSentFromMailbox = $MessageSentFromAllObject->mailbox ."#". $MessageSentFromAllObject->host; //Everything before and after the “#” of the sender
$MessageSentFromName = $MessageSentFromAllObject->personal; //The name of the person who sent the email
$toArray = searchRecipient($MessageSentToMailbox); //Find the correct person to send the email to
if($toArray == FALSE) //If the alias they entered doesn’t exist…
{
$bounceback = 'Sorry the email in your message does not appear to be correct';
/* Send a bounceback email */
$mail = new PHPMailer(); // defaults to using php “mail()”
$mail -> ContentType = 'text/plain'; //Plain email
$mail -> IsHTML(false); //No HTML
$the_body = wordWrap($bounceback, 70); //Word wrap to 70 characters for formatting
$from_email_address = 'name#domain.com';
$mail->AddReplyTo($from_email_address, "domain.Com");
$mail->SetFrom($from_email_address, "domain.Com");
$address = $MessageSentFromMailbox; //Who we’re sending the email to
$mail->AddAddress($address, $MessageSentFromName);
$mail->Subject = 'Request'; //Subject of the email
$mail->Body = $the_body;
if(!$mail->Send()) //If the mail fails, send to customError
{
customError(1, $mail->ErrorInfo, "anon-email.php", "sending the email");
}
}
else //If the candidate address exists, forward on the email
{
$mail = new PHPMailer(); // defaults to using php “mail()”
$mail -> ContentType = 'text/plain'; //Plain E-mail
$mail -> IsHTML(FALSE); //No HTML
$the_body = wordwrap($Body, 70); //Wordwrap for proper email formatting
$from_email_address = "$MessageSentFromMailbox";
$mail->AddReplyTo($from_email_address);
$mail->SetFrom($from_email_address);
$address = $toArray[1]; //Who we’re sending the email to
$mail->AddAddress($address, $toArray[0]); //The name of the person we’re sending to
$mail->Subject = $EmailHeaders->subject; //Subject of the email
$mail->Body = ($the_body);
if(!$mail->Send()) //If mail fails, go to the custom error
{
customError(1, $mail->ErrorInfo, "anon-email.php", "sending the email");
}
}
/* Mark the email for deletion after processing */
imap_delete($connection, $MID);
}
imap_expunge($connection); // Expunge processes all of the emails marked to be deleted
imap_close($connection);
function searchRecipient() // function to search the database for the real email
{
global $MessageSentToMailbox; // bring in the alias email
$email_addr = mysql_query("SELECT email FROM tbl WHERE source='$MessageSentToMailbox'"); // temp store of the real email
$row = mysql_fetch_array($email_addr); //making temp store of data for use in program
if(empty($row['email']))
{
return FALSE;
}
else /* Else, return find the person's name and return both in an array */
{
$results = mysql_query("SELECT * FROM tbl WHERE email = '$email_addr'"); // temp store of both queries from this function
$row = mysql_fetch_array($results, $email_addr); //making temp store of data for use in program
$name = $row['author']; // taking the author data and naming its variable
return array($name, $email_addr); // this is the name and the real email address to be used in function call
}
}
function customError($errno, $errstr, $file, $line)
{
error_log("Error: [$errno] $errstr in $file at line number: $line",1, "name#domain.com","From: name#domain.com.com");
die();
}
Here is the first thing I would try:
It would appear that your function searchRecipient isn't being passed a parameter. Rather than use the global keyword, I would define it in your function call. Also, mysql_fetch_array does not pass back an associative array, which is what you are using in your next step. I would change that to mysql_fetch_assoc (it's the same thing essentially). There are also a few other minor syntax corrections in this function. Here are my proposed changes to that function. I think this should fix your problem. Or at least get you moving forward.
function searchRecipient($MessageSentToMailbox) // function to search the database for the real email
{
$email_addr = mysql_query("SELECT email FROM tbl WHERE source='$MessageSentToMailbox'"); // temp store of the real email
$row = mysql_fetch_assoc($email_addr); //making temp store of data for use in program
if(empty($row['email']))
{
return FALSE;
}
else /* Else, return find the person's name and return both in an array */
{
$email_addr = $row['email'];
$results = mysql_query("SELECT * FROM tbl WHERE email = '$email_addr'"); // temp store of both queries from this function
$row = mysql_fetch_assoc($results); //making temp store of data for use in program
$name = $row['author']; // taking the author data and naming its variable
return array($name, $email_addr); // this is the name and the real email address to be used in function call
}
}
You could also combine this into one query and make it a little easier. Here is that solution.
function searchRecipient($MessageSentToMailbox)
{
$results = mysql_query("SELECT email, author FROM tbl WHERE source='$MessageSentToMailbox'");
$row = mysql_fetch_assoc($results);
if(empty($row['email']) || empty($row['author'])) return false;
return array($row['email'], $row['author']);
}