Does in_array have length restriction in PHP - php

I have an array to be searched from numerous order_status_id
$order_status_id is pulled from a mysqli_query, which is working perfect for other conditional checks (in_array)
Below is the full code -
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$con=mysqli_connect("localhost","abc_admin","abc123!","abc_store");//database connection
date_default_timezone_set("Asia/Kolkata");
$store_name_query = mysqli_query($con,"SELECT `value` FROM `oc_setting` WHERE `key`='config_name' AND `store_id`='0' AND `code`='config'");
$store_name_result = mysqli_fetch_array($store_name_query);
$store_name = $store_name_result['value'];
$date = date('Y-m-d');
$date_time = date('Y-m-d H:i:s');
$date_time_formatted = date("d M Y h:i:s A",strtotime($date_time));
$return_details = "SELECT * FROM `oc_return` WHERE `return_status_id`='1'";
if($return_data = mysqli_query($con,$return_details))
{
$count = mysqli_num_rows($return_data);
echo "<h1> $count Returns Processing</h1>";
require_once('PHPMailerAutoload.php');
while ($row=mysqli_fetch_array($return_data))
{
$return_id = $row['return_id'];
echo "Fetching Details for Return ID $return_id<br><br>";
$order_id = $row['order_id'];
$customer_id = $row['customer_id'];
$firstname = mb_convert_case($row['firstname'], MB_CASE_TITLE,"UTF-8");
$lastname = mb_convert_case($row['lastname'], MB_CASE_TITLE,"UTF-8");
$customer_name = $firstname." ".$lastname;
$email = $row['email'];
$product = $row['product'];
$comment = $row['comment'];
$return_date = $row['date_added'];
$date_added = date("d M Y",strtotime($row['date_added']));
$resolution_date = date('d-M-Y', strtotime($date_added. ' + 15 days'));
$resolution_date_in_format = date('Y-m-d H:i:s', strtotime($return_date. ' + 15 days'));
$mobile = $row['telephone'];
$return_reason_id = $row['return_reason_id'];
$order_date = $row['date_ordered'];
$order_details = mysqli_query($con,"SELECT * FROM `oc_order` WHERE `order_id`='$order_id'");
echo "Fetching Details for Order ID $order_id<br><br>";
while ($order_total = mysqli_fetch_array($order_details))
{
$total = str_replace(".0000","",$order_total['total']);
$order_status_id = $order_total['order_status_id'];
echo "$order_status_id<br><br>";
// CONDITIONAL CHECKS
$shipped_ud = "3 || 32";
$shipped_ud_status = explode(' || ',$shipped_ud);
$ready_process = "15 || 23 || 39";
$ready_process_status = explode(' || ',$ready_process);
$other_status_ids = "1 || 7 || 11 || 13 || 21 || 22 || 24 || 25 || 26 || 27 || 28 || 29 || 30 || 31 || 33 || 34 || 35 || 36 || 37 || 38 || 40";
$other_statuses = explode(' || ', $other_status_ids);
// IF ORDER IS IN PROCESSING STATE ↓ //
if($order_status_id == '2')
{
$cancel_comment = 'Order cancelled by Customer';
$cancel_order = mysqli_query($con,"UPDATE `oc_order` SET `order_status_id`='24' WHERE `order_id`='$order_id'");
$cancel_order_history = mysqli_query($con,"INSERT INTO `oc_order_history` (`order_id`,`order_status_id`,`notify`,`comment`,`date_added`) VALUES ('$order_id','24','1','$cancel_comment','$date_time')");
echo "Order has been cancelled<br><br>";
$update_return_table = mysqli_query($con,"UPDATE `oc_return` SET `return_status_id`='4',`return_action_id`='4' WHERE `return_id`='$return_id'");
$return_history_comment = "Your return request to cancel the order has been successfully processed. We are sorry to see you go away!";
$add_return_history = mysqli_query($con,"INSERT INTO `oc_return_history` (`return_id`, `return_status_id`, `notify`, `comment`, `date_added`) VALUES ('$return_id','4','1','$return_history_comment','$date_time')");
//Send Email to customer if order is in processing state //
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(true); // telling the class to use SMTP
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
try {
$mail->Host = "ssl://abcabc123.com"; // SMTP server
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "ssl://abcabc123.com"; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "help#abcabc123.com"; // SMTP account username
$mail->Password = "Tmob134624!"; // SMTP account password
$mail->AddReplyTo('help#abcabc123.com', 'AbcAbc123');
$mail->AddAddress("$email", "$customer_name");
$mail->SetFrom('help#abcabc123.com', 'AbcAbc123');
$mail->addCustomHeader('In-Reply-To', "Order Return/Cancellation Request $return_id - Order ID $order_id");
$mail->XMailer = ' ';
$Subject = "Order Cancellation Request | Order ID $order_id";
$mail->Subject = "$Subject";
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
// Message //
$mail->Body = " \r\n";
// Body of Email trimmed
$mail->Send();
}
catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
}
// IF ORDER IS SHIPPED OR IN TRANSIT ↓ //
else if(in_array($order_status_id,$shipped_ud_status))
{
$cancel_if_shipped = mysqli_query($con,"INSERT INTO `oc_order_history` (`order_id`,`order_status_id`,`notify`,`comment`,`date_added`) VALUES ('$order_id','24','1','Order Shipped, Cancellation Requested by Customer','$date_time')");
$update_return_for_shipped = mysqli_query($con,"UPDATE `oc_return` SET `return_status_id`='3',`return_action_id`='4' WHERE `return_id`='$return_id'");
//Email //
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(true); // telling the class to use SMTP
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
try {
$mail->Host = "ssl://abcabc123.com"; // SMTP server
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "ssl://abcabc123.com"; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "help#abcabc123.com"; // SMTP account username
$mail->Password = "Tmob134624!"; // SMTP account password
$mail->AddReplyTo('help#abcabc123.com', 'AbcAbc123');
$mail->AddAddress("$email", "$customer_name");
$mail->SetFrom('help#abcabc123.com', 'AbcAbc123');
$mail->addCustomHeader('In-Reply-To', "Order Return - Order ID $order_id");
$mail->XMailer = ' ';
$Subject = "Return Request Update | Order ID $order_id";
$mail->Subject = "$Subject";
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
// Message //
$mail->Body = " \r\n";
// Body of Email trimmed
$mail->Send();
}
catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
}
// IF ORDER IS PROCESSED OR IN READY TO SHIP STATE ↓
else if(in_array($order_status_id,$ready_process_status))
{
// SEND EMAIL TO CUSTOMER
//Email //
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(true); // telling the class to use SMTP
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
try {
$mail->Host = "ssl://abcabc123.com"; // SMTP server
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "ssl://abcabc123.com"; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "info#abcabc123.com"; // SMTP account username
$mail->Password = "Tmob134624!"; // SMTP account password
$mail->AddReplyTo('info#abcabc123.com', 'AbcAbc123');
$mail->AddAddress($email, $customer_name);
$mail->SetFrom('info#abcabc123.com', 'AbcAbc123');
$mail->addCustomHeader('In-Reply-To', "Order Return Request ID $return_id - Order ID $order_id");
$mail->XMailer = ' ';
$Subject = "Return Request Update | Order ID $order_id";
$mail->Subject = "$Subject";
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
// Message //
$mail->Body = " \r\n";
// Body of Email trimmed
$mail->Send();
}
catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
// Send SMS to Processing Team
// SMS Code //
$msg = "URGENT : ".$store_name."
Order ID ".$order_id."
Customer - ".$customer_name."
has been cancelled by Customer. Please DO NOT process this order.";
// $length= strlen($msg);
// $sms_count = ceil($length/160);
$sms_text = mysqli_real_escape_string($con,$msg);
$cc_mobile = '12456789';
////////////Promotion API Key 5y6zMwrqCEOs5oGJ6xyVZg //////////////////
$encode= rawurlencode($msg);
//request parameters array
$requestParams = array(
'channel' => '2',
'APIKey' => 'J8yAjtZkTUqMnDy6SDQN6Q',
'senderid' => 'ABCABC',
'Number' => $cc_mobile,
'Text' => $encode,
'DCS' => '0',
'Route' => '1',
'Flashsms' => '0',
);
//merge API url and parameters
$apiUrl = "https://login.smshub.com/api/mt/SendSMS?";
foreach($requestParams as $key => $val){
$apiUrl .= $key.'='.($val).'&';
}
$apiUrl = rtrim($apiUrl, "&");
//API call
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$apiUrl);
curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_TIMEOUT,60);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch,CURLOPT_POSTFIELDS,0);
$data = curl_exec($ch);
if (curl_errno($ch) > 0) {
print 'There was a cURL error: ' . $curl_error($ch);
}
$json = json_decode($data);
$JobID = $json->{'JobId'};
curl_close($ch);
echo "Order Cancellation message sent to $cc_mobile <br><br>";
// End of SMS Code//
$cancel_if_processed = mysqli_query($con,"INSERT INTO `oc_order_history` (`order_id`,`order_status_id`,`notify`,`comment`,`date_added`) VALUES ('$order_id','24','1','Customer Requested Cancellation','$date_time')");
$cancel_if_processed = mysqli_query($con,"INSERT INTO `oc_order_history` (`order_id`,`order_status_id`,`notify`,`comment`,`date_added`) VALUES ('$order_id','24','1','Order Shipped, Cancellation Requested by Customer','$date_time')");
$update_return_for_processed = mysqli_query($con,"UPDATE `oc_return` SET `return_status_id`='13',`return_action_id`='4' WHERE `return_id`='$return_id'");
}
else if($order_status_id == '17')
{
$return_processing = mysqli_query($con,"UPDATE `oc_return` SET `return_status_id`='7' WHERE `return_id`='$return_id'");
echo "Return Status Updated to <strong>Processing</strong> for Return ID $return_id<br><br>";
$processing_comment = mysqli_real_escape_string($con,"<p><i>We are sorry that you are unsatisfied with your purchase from our store.</i></p><p>Your Return Request $return_id has been received and is being looked into by our Returns Processing Team.</p><p>We request you to please read our <a href='https://www.abcabc123.com/cancellation-and-refund' target='_blank' style='text-decoration:none;'>Cancellation & Return Policy</a></p><p>All decisions regarding Returns shall be final & binding as per our policy.<p><p>We shall update you latest by $resolution_date regarding your return as our minimum TAT is 15 days.<p>");
$return_history = mysqli_query($con,"INSERT INTO `oc_return_history`(`return_id`,`return_status_id`,`notify`,`comment`,`date_added`) VALUES ('$return_id','7','1','$processing_comment','$date_time')");
$resolution_comment = "Your return has been marked as Complete/Processed by our Returns Processing Team as the same does not meet our Cancellation and Returns policy for Refund or Replacement.";
$return_history_resolution = mysqli_query($con,"INSERT INTO `oc_return_history`(`return_id`,`return_status_id`,`notify`,`comment`,`date_added`) VALUES ('$return_id','3','0','$resolution_comment','$resolution_date_in_format')");
$cancel_if_delivered = mysqli_query($con,"INSERT INTO `oc_order_history` (`order_id`,`order_status_id`,`notify`,`comment`,`date_added`) VALUES ('$order_id','40','1','Order Delivered, Return Requested by Customer','$date_time')");
$update_order_for_delivered = mysqli_query($con,"UPDATE `oc_order` SET `order_status_id`='40' WHERE `order_id`='$order_id'");
$update_return_for_delivered = mysqli_query($con,"UPDATE `oc_return` SET `return_status_id`='7' WHERE `return_id`='$order_id'");
//Email Receiver//
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(true); // telling the class to use SMTP
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
try {
$mail->Host = "ssl://abcabc123.com"; // SMTP server
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "ssl://abcabc123.com"; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "help#abcabc123.com"; // SMTP account username
$mail->Password = "Tmob134624!"; // SMTP account password
$mail->AddReplyTo('help#abcabc123.com', 'AbcAbc123');
$mail->AddAddress("$email", "$firstname $lastname");
$mail->SetFrom('help#abcabc123.com', 'AbcAbc123');
$mail->AddReplyTo('help#abcabc123.com', 'AbcAbc123');
$mail->addCustomHeader('In-Reply-To',"Return ID $return_id");
$mail->XMailer = ' ';
$mail->Subject = "Your Return Request ID $return_id is being processed";
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->Body = " \r\n ";
// Body of Email trimmed
$mail->Send();
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
// EMAIL SENT ↑
}
// OTHER STATUSES
else if(in_array($order_status_id,$other_statuses))
{
echo "Checked positive for <span style='color:red;'>Other</span><br>";
$update_return_for_other = mysqli_query($con,"UPDATE `oc_return` SET `return_status_id`='3' WHERE `return_id`='$return_id'");
$return_history_for_other = mysqli_query($con,"INSERT INTO `oc_return_history`(`return_id`,`return_status_id`,`notify`,`comment`,`date_added`) VALUES ('$return_id','3','1','Return Invalid','$date_time')");
echo "Order not to be processed<br><br>";
}
// RETURNS UPDATED ↑
else
{
echo "Nothing to be processed <br><br>";
}
}
}
}
?>
$update_return_for_other mysqli_query works like charm for other checks being done before this check
My Code is processing other in_array checks which are small but, not this one!
Don't know what is the issue. Please help

Related

How to send email based on two tables after insert query?

I'm trying to send an email update to users from the candidates_table but the content of the email comes from the jobs_list table. Please see my attempt below, I'm using PHPmailer and I'm getting no errors. The script below is the handling script for a form.
The data from the jobs_list is being displayed, however, the candidates_table data is not.
This is just below the insert statement:
UPDATE:
$vac_last_id = $dbh->lastInsertId();
echo $vac_last_id;
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE id=:id");
$sql->bindValue(':id', $vac_last_id, PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
while($row = $sql->fetch()) {
$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('', '- Vacancies');
$mail->addReplyTo('', '- Vacancies');
$mail->Subject = "";
//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
$mail->Body = 'THE BODY...';
//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 = $dbh->prepare("SELECT * FROM candidates_table WHERE receive_email = 2");
if ($mysql->execute()) {
$mysql->setFetchMode(PDO::FETCH_ASSOC);
}
foreach ($mysql as $row) { //This iterator syntax only works in PHP 5.4+
$mail->addAddress($row['email_address'], $row['full_name']);
if (!$mail->send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email_address"]) . ') ' . $mail->ErrorInfo . '<br />';
break; //Abandon sending
} else {
echo "Message sent to :" . $row['full_name'] . ' (' . str_replace("#", "#", $row['email_address']) . ')<br />';
//Mark it as sent in the DB
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
}
}
Insert Job List in job_listing table. Find, current job_listing table id. Fetch it again and find all candidates to send email.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require 'PHPMailer/PHPMailerAutoload.php';
include 'db_connect.php';
$contact_name = $_POST['contact_name'];
$latest_job_id = 0;
$stmt = $dbh->prepare("INSERT INTO jobs_list (jobTitle, company_name, job_details, salary_info, salary_extra, apply_link, company_email, company_phone, TimeStamp) VALUES (:jobTitle, :company_name, :job_details, :salary_info, :salary_extra, :apply_link, :company_email, :company_phone, NOW())");
$stmt->bindParam(':jobTitle', $_POST['jobTitle'], PDO::PARAM_STR);
$stmt->bindParam(':company_name', $_POST['company_name'], PDO::PARAM_STR);
$stmt->bindParam(':job_details', $_POST['job_details'], PDO::PARAM_STR);
$stmt->bindParam(':salary_info', $_POST['salary_info'], PDO::PARAM_STR);
$stmt->bindParam(':salary_extra', $_POST['salary_extra'], PDO::PARAM_STR);
$stmt->bindParam(':apply_link', $_POST['apply_link'], PDO::PARAM_STR);
$stmt->bindParam(':company_email', $_POST['company_email'], PDO::PARAM_STR);
$stmt->bindParam(':company_phone', $_POST['company_phone'], PDO::PARAM_STR);
$stmt->execute();
$latest_job_id = $dbh->lastInsertId(); //#Nana Comments: Get latest Job Listing ID
if($latest_job_id > 0){
/*#Nana Comments: If Inserted Successfully, '$latest_job_id' will be greater than 0.*/
$mail_error_text = ""; //#Nana Comments: If email not sent, then it will store the email address
/*#Nana Comments: Select recent job listing details.*/
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE id = :id LIMIT 0, 1");
$sql->bindParam(':id', $latest_job_id);
if ($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = ''; // Enable TLS encryption, `ssl` also accepted
$mail->Port = ''; // TCP port to connect to
$mail->setFrom('', 'sender');
while ($row = $sql->fetch()) {
$new_company_email = trim($row['company_email']);
$new_company_name = trim($row['company_name']);
/*#Nana Comments: Select all candidates and send email */
$load_candidate = $dbh->prepare("SELECT * FROM candidates_table");
if ($load_candidate->execute()) {
$load_candidate->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $load_candidate->fetch()) {
$mail->addAddress($row['email_address']); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New Vacancy';
$mail->Body = 'mail body in here';
$mail->AltBody = '';
if(!$mail->send()){
$mail_error_text .= "Mailer Error (" . str_replace("#", "#", $row["email_address"]) . ') ' . $mail->ErrorInfo . '<br />';
}
$mail->clearAddresses(); // Clear all addresses for next loop
$mail->clearAttachments(); // Clear all attachments for next loop
}
}
}
}
if($mail_error_text != ""){
echo "<b>Email not sent to:</b><br>".$mail_error_text;
}
} else {
echo "Job Listing Insertion Fails";
}
} else {
echo "access denied";
}?>

PHP sending emails to but not text

I am trying to send emails to phones that have Verizon numbers. Here is my code right now
<?php require('includes/config.php');
function Send( $ToEmail, $MessageHTML, $MessageTEXT) {
require_once ( 'classes/phpmailer/phpmailer.php' ); // Add the path as appropriate
$Mail = new PHPMailer();
$Mail->IsSMTP(); // Use SMTP
$Mail->Host = "box405.bluehost.com"; // Sets SMTP server
$Mail->SMTPDebug = 2; // 2 to enable SMTP debug information
$Mail->SMTPAuth = TRUE; // enable SMTP authentication
$Mail->SMTPSecure = "ssl"; //Secure conection
$Mail->Port = 465; // set the SMTP port
$Mail->Username = 'techsupport#test.com'; // SMTP fake account username
$Mail->Password = 'password1'; // SMTP fake account password
$Mail->Priority = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
$Mail->CharSet = 'UTF-8';
$Mail->Encoding = '8bit';
$Mail->ContentType = 'text/html; charset=utf-8\r\n';
$Mail->FromName = 'Tech support';
$Mail->WordWrap = 900; // RFC 2822 Compliant for Max 998 characters per line
$Mail->AddAddress( $ToEmail ); // To:
$Mail->isHTML( TRUE );
$Mail->Body = $MessageHTML;
$Mail->AltBody = $MessageTEXT;
$Mail->Send();
$Mail->SmtpClose();
if ( $Mail->IsError() ) { // ADDED - This error checking was missing
return FALSE;
}
else {
return TRUE;
}
}
$stmt = $db->prepare("select phone From members where phone not like 'no';");
$stmt->execute();
$result = $stmt->fetchAll();
$ToEmail = $result[0][0];
$ToName = 'techsupport';
$MessageHTML = "test";
$MessageTEXT = 'test';
$Send = Send( $ToEmail, $MessageHTML, $MessageTEXT);
if ( $Send ) {
echo "<h2> Sent OK</h2>";
}
else {
echo "<h2> ERROR</h2>";
}
die;
?>
this works when I try to send emails but when I use it to send texts it says sent but I do not receive anything. I know this is not because of the address because I use the same address when I text myself from gmail and it is not the sql query because I have tested it . I Think the problem is in the smtp or phpmailer for I have not used either of those a lot. Also the code runs though and prints out the SENT OK echo but nothing goes through and no errors.
[EDIT] To answer ironcito's question I am sending the email to
phonenumber#vtext.com
I know this works because I have used the same address through gmail.
I think this might be because you push the content to the mail (body) before you set the content (messagehtml/messagetext), which creates an empty email. Try changing these around, that might be the solution.

PHPMailer not working consistently

I have a web app using PHP, MySQL, and PHPMailer to send emails. The issue I am having is PHPMailer will send some of the emails, but not always. I'm thinking maybe it is because different list of emails have data issues? Below is my code that loops through the email addresses and send some, but not all the emails. I have tried to catch errors, but I can't see any in the logs.
How can I debug what is going on, and why some don't send?
else if($current_version == 'PROD'){
date_default_timezone_set('America/New_York');
require 'PHPMailer-master/PHPMailerAutoload.php';
$pageURL = 'xxxxxx';
$subject = "xxxxx ";
$body = "xxxxxx \r\n";
$body .= "xxxxx \r\n \r\n";
$body_html = str_replace("\r\n","<br/>",$body);
try {
$mail = new PHPMailer();
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "xxx#xxxx.com";
$mail->Password = "xxxx";
$mail->setFrom('xxxxx#xxxx.com', 'xxxx');
$mail->addReplyTo('xxxx#xxxx.com', 'xxxx');
$mail->Subject = $subject;
$mail->Body = $body_html;
$mail->AltBody = $body;
$sql_email_list = "SELECT email FROM tbl_email
WHERE distro_name='xxxxs'
AND is_active='Y' ";
$result_email_list = mysql_query($sql_email_list);
$num_email_list = mysql_num_rows($result_email_list);
$lost_email_list = mysql_result($result_email_list,0,'email');
$lost_email_array = explode(";",$lost_email_list);
foreach ($lost_email_array as $key => $val){
$mail->AddAddress($val);
if($carrier_email_flag_global == 'ON'){
$mail->send();
$mail->ClearAllRecipients();
$mail->ClearAttachments();
echo '<hr>Email Sent to: '.$val;
}
}
$sql_email_one = "SELECT table2.email
FROM table1
INNER JOIN table2 ON table1.cntct = table2.cntct_id
WHERE id='$id' ";
$result_email_one = mysql_query($sql_email_one);
$num_email_one = mysql_num_rows($result_email_one);
for($iiz=0;$iiz<$num_email_one;$iiz++){
$one_email = mysql_result($result_email_one,$iiz,'email');
$mail->AddAddress($one_email);
if($carrier_email_flag_global == 'ON'){
$mail->send();
$mail->ClearAllRecipients();
$mail->ClearAttachments();
echo '<hr>Email Sent to: '.$val;
}
}
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
echo '<hr>ERROR 001';
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
echo '<hr>ERROR 002';
}
}

phpmailer - email not send in gmail

I am having problem with sending mail using phpmailer. I am a beginner programmer. I am trying to make contact form. My code is as follow(submit.php). Please suggest me.. Thanks in advance .
session_start();
require_once 'libs/phpmail/PHPMailerAutoload.php';
$errors = array();
if(isset($_POST['name'], $_POST['phone'],$_POST['mail'],$_POST['message'])){
$fields = array(
'name' => $_POST['name'],
'phone' => $_POST['phone'],
'email' => $_POST['mail'],
'message' => $_POST['message']
);
foreach ($fields as $field => $data) {
if(empty($data)){
$errors[] = 'The '. $field . ' field is required';
}
}
if(empty($errors)){
$m = new PHPMailer;
$m -> isSMTP();
$m -> SMTPAuth = true;
//$m -> SMTPDebug = 2;
$m -> Host = 'smtp.gmail.com';
$m -> Username = 'xxxx#gmail.com';
$m -> Password = 'xxxx';
$m -> SMTPSecure = 'ssl';
$m -> Port = 465;
$m -> isHTML();
$m -> Subject = 'Contact form submitted';
$m -> Body = 'From: ' . $fields['name']. '('. $fields['phone'] . $fields['email']. ')'.'<p>' .$fields['message'] .'</p> ';
$m -> FromName = 'Contact';
// $m ->addReplyTo($fields['email'], $fields['name']);
$m -> addAddress('ssss#gmail.com', 'xxxxxxxx');
if($m->send()){
header('Location: thanks.php');
die();
}else{
$errors[] = 'Sorry could not send email. Please try again';
}
}
}else{
$errors[] = 'some thing went wrong';
}
$_SESSION['error'] = $errors;
$_SESSION['field'] = $fields;
header('Location: form.php');
My setting phpmailer, everything works
function __construct ($to, $subject, $body) {
date_default_timezone_set('Etc/UTC');
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
$mail->CharSet = 'UTF-8';
//Set the hostname of the mail server
$mail->Host = "mail.xxxxxx.com";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
$mail->AuthType = 'PLAIN';
//Username to use for SMTP authentication
$mail->Username = "xxxx";
//Password to use for SMTP authentication
$mail->Password = "xxxx";
//Set who the message is to be sent from
$mail->setFrom('erp#xxxxxx.com');
//Set an alternative reply-to address
//$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress($to);
//Set the subject line
$mail->Subject = $subject;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML($body);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
$this->mail = $mail;
}
function SendMail () {
//send the message, check for errors
if (!$this->mail->send()) {
return "Mailer Error: " . $this->mail->ErrorInfo;
} else {
return true;
}
}
// using
$email = $this->request->getPost('email');
$smtp = new \SmtpClient($email, 'Test', $template);
$result = $smtp->SendMail();
Remove
$m -> Subject = 'Contact form submitted';
And try again.
When I remove the subject it worked.

I'm trying to use PHPMailer to send multiple e-mails (different email to each recipient)

First time posting so any help greatly appreciated...
I'm happy the SQL query works and returns two 2 rows
I'm happy to leave message as "hello" for now
I've looked through many answers and none solve my problem
This function will send the mail to only the first (of 2) recipient but not the second.
If anyone could tell me where I am going wrong I would be very grateful...
public function sendOrderEmail($customer_order_id)
{
$sql3=" SELECT DISTINCT w.user_id AS supplier_id,
s.trading_name AS supplier_name,
s.contact_email AS supplier_email
FROM supplier_info AS s
JOIN wine AS w ON w.user_id = s.id
JOIN order_detail AS o ON o.wine_id = w.id
WHERE o.order_no_id = :customer_order_id ORDER BY supplier_id DESC;";
$query3 = $this->db->prepare($sql3);
$query3->execute(array(':customer_order_id' => intval($customer_order_id)));
//$result3 = $query3->fetchAll();
while($row3 = $query3->fetch(PDO::FETCH_ASSOC)){
// while ($row3 = $query3->fetch()) {
$supplier_name = $row3['supplier_name'];
$supplier_email = $row3['supplier_email'];
// foreach($result3 as $key => $output){
//$supplier_id = $output->supplier_id;
// $supplier_email = $output->email; */
$mail = new PHPMailer;
if (EMAIL_USE_SMTP) {
$mail->IsSMTP();
$mail->SMTPDebug = PHPMAILER_DEBUG_MODE;
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
if (defined('EMAIL_SMTP_ENCRYPTION')) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
} else {
$mail->IsMail();
}
// Build email body
$message = "<p>hello</p>";
// fill mail with data
$mail->isHTML(true);
$mail->From = "billyjlennon#gmail.com";
$mail->FromName = "Me";
$mail->AddAddress($supplier_email);
$mail->Subject = "Your request ";
$mail->Body = $message;
// final sending and check
if($mail->Send()) {
$_SESSION["feedback_positive"][] = FEEDBACK_CONTACT_MAIL_SENDING_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_CONTACT_MAIL_SENDING_ERROR . $mail- >ErrorInfo;
return false;
}
}
First up, you should really check the PHPMailer documentation first since there is an example that does exactly this. You can't have been looking too hard.
In your code, don't create a new PHPMailer instance every time around the loop - all the things that remain the same (isSmtp, Host, Port, etc) should be set once, before the loop. Inside the loop you should do these things:
Set the message body
Set the recipient
Send the message
Store any errors
Clear the recipient list (use clearAllRecipients())
You've also got return statements after your send check - these will exit your function completely, so it will never send more than one message. You should gather the errors as you go through your list and present (or return) them at the end.
I used a while loop just around the addAddress as suggested by #synchro above. Foreach iterator syntax wouldn't work as I'm using PHP 5.3 (as per comment in the link to PHPmailer above).
Then I took the return outside the while loop and everything worked just fine.
This is the code that worked:
(Any improvements on it gratefully accepted)
public function sendOrderEmail($customer_order_id)
{
$sql3 = " SELECT DISTINCT w.user_id AS supplier_id,
s.trading_name AS supplier_name,
s.contact_email AS supplier_email
FROM supplier_info AS s
JOIN wine AS w ON w.user_id = s.id
JOIN order_detail AS o ON o.wine_id = w.id
WHERE o.order_no_id = :customer_order_id ORDER BY supplier_id DESC;";
$query3 = $this->db->prepare($sql3);
$query3->execute(array(':customer_order_id' => intval($customer_order_id)));
$mail = new PHPMailer;
if (EMAIL_USE_SMTP) {
$mail->IsSMTP();
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
$mail->SMTPDebug = PHPMAILER_DEBUG_MODE;
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
$mail->SMTPKeepAlive = true;
if (defined('EMAIL_SMTP_ENCRYPTION')) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
} else {
$mail->IsMail();
}
$mail->isHTML(true);
$mail->From = "billyjlennon#gmail.com";
$mail->FromName = "Me";
while ($row3 = $query3->fetch(PDO::FETCH_ASSOC)) {
// Build email body
$message = "<p>hello</p>";
// fill mail with data
$mail->AddAddress($row3['supplier_email']);
$mail->Subject = "Your request to " . $row3['supplier_name'];
$mail->Body = $message;
// final sending and check
if ($mail->Send()) {
// $_SESSION["feedback_positive"][] = FEEDBACK_CONTACT_MAIL_SENDING_SUCCESSFUL;
//return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_CONTACT_MAIL_SENDING_ERROR . $mail->ErrorInfo;
// return false;
break;
}
$mail->ClearAddresses();
}
return true;
}

Categories