Send email order OPENCART - php

I can't say it directly, I have to explain what I want to do so you understand.
I have made an extension whereby orders are taken by 2 employees in the following way:
1 you
1 me
So in order.
I want to send the orders directly to the email. But I want to send the order exactly to the employee who took the order.
In the database, this table has the name "retrieved" in which there are 2 numbers: 5 and 4.
If it is 5 = employee 1, if it is 4 = employee 2.
This is the code I made that should send orders to the email that took the order. But what do you see? It sends the orders, only to the FIRST email. Even if the order is accepted by the other person, it still goes into the first email.
I have tried variations with if, ssmd but to no avail. That's why I have to ask here, what can I do?
Also note that this module is inserted in (public_html/catalog/model/checkout/order.php). I don't know if this is right or not.
`
$order_query = $this->db->query("SELECT preluat FROM " . DB_PREFIX . "order WHERE order_id = '" . (int)$order_id . "'");
$order = $order_query->row;
if ($order) {
$lady1_email = "email1#name.com";
$lady2_email = "email2#name.com";
switch ($order['preluat']) {
case '4':
$to_email = $lady1_email;
break;
case '5':
$to_email = $lady2_email;
break;
}
if ($to_email != "") {
$subject = "New order received";
$body = "Dear Lady,\n\nA new order has been allocated to you. Please check your order list and start processing it as soon as possible.\n\nOrder details:\nOrder ID: " . $order['order_id'] . "\nCustomer Name: " . $order['firstname'] . " " . $order['lastname'] . "\nOrder Total: " . $order['total'] . "\n\nBest regards,\nYour Employer";
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->hostname = $this->config->get('config_smtp_host');
$mail->username = $this->config->get('config_smtp_username');
$mail->password = $this->config->get('config_smtp_password');
$mail->port = $this->config->get('config_smtp_port');
$mail->timeout = $this->config->get('config_smtp_timeout');
$mail->setTo($to_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender($order['store_name']);
$mail->setSubject($subject);
$mail->setText($body);
$mail->send();
}
}*/
I want the code to work as I have detailed. To send orders correctly to the employees email depending on how the order is approved.

Related

What is an efficient way to send email to many users in PHP

I have a database of over 12,000 users and I am trying to send an email to all of them, each with a specific information based on their information on the database. I have made this email to send when a cron runs on Sundays by 6am and I completed the feature last friday and it ran on sunday, i.e, Yesterday. Here is what happened.
1.) The email kept sending all day from 6am to 7pm
2.) By that time, it had sent only to 750 users
3.) After that it stopped completely for reasons I don't know
PS:
I am sending the emails using PHPMailer, with a template and I use a loop to loop over all users and perform calculations for each user, fill in the template with the information then send the email.
Below is a code snippet showing what I do...
foreach($users as $user){
// Construct the email template
$htmlContent = file_get_contents(__DIR__ . '/../../templates/weekly_spending_template.html');
// Replace some place holders with user's custom information.
$htmlContent = preg_replace('/\$bars/', $bars, $htmlContent);
$htmlContent = preg_replace('/\$labels/', $labels, $htmlContent);
$htmlContent = preg_replace('/\$total/', $currency . ' ' . number_format($total, 0), $htmlContent);
$htmlContent = preg_replace('/\$budget/', $currency . ' ' . number_format($budget, 0), $htmlContent);
$htmlContent = preg_replace('/\$first_name/', ucfirst($user->first_name), $htmlContent);
$htmlContent = preg_replace('/\$remark/', $remark, $htmlContent);
$htmlContent = preg_replace('/\$percentage_difference/', $percentage_difference, $htmlContent);
$htmlContent = preg_replace('/\$others/', $others, $htmlContent);
try {
// Setup email parameters
$mail = new PHPMailer(true);
$subject = "Your weekly spending breakdown";
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->AddAddress($user->email, ucfirst($user->first_name) . ' ' . ucfirst($user->last_name));
$mail->Username = "mymail#example.com";
$mail->Password = "myPassW0rd";
$mail->SetFrom('mymail#example.com', 'Name');
$mail->AddReplyTo("mymail#example.com", "Name");
$mail->Subject = $subject;
$mail->Body = $htmlContent;
$mail->isHTML(true);
if (!$mail->send()) {
echo "Message was not sent.\n";
echo 'Mailer error: ' . $mail->ErrorInfo . "\n";
} else {
echo "Message has been sent.\n";
}
} catch (\Exception $ex) {
echo $ex->getMessage();
}
}
Please, can anyone give me suggestions on how to make this process more efficient, faster or better options for achieving this goal? Thanks.
You might consider using swiftmailer (below link), as it has mostly everthing you want and is used in many products and frameworks, so you can be sure it's fairly stable.
https://swiftmailer.symfony.com/docs/sending.html#sending-emails-in-batch
And you can only send 500 mails/per day #20 mails/per hour
See: https://support.google.com/a/answer/2956491#sendinglimitsforrelay
Just separate them by comma, like
$email_to = "youremailaddress#yourdomain.com, emailtwo#yourdomain.com, John Doe <emailthree#example.com>"
For more details check this link:- PHP send mail to multiple email addresses

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 code : email not send

my problem is i have a code to send email to users when click in some button its works for me in localhost but not working when i push it in heroku server
<?php
if (isset($_POST['submitcmt']) && $_POST['token'] == $dcs_user_info['token']) {
//get rows in watchlist table if contest_id (job_id)==contest_id in database $watchlist_table = mysqli_query($conn, "SELECT * FROM watchlist WHERE contest_id='$contest_id'") or die("Error: " . mysqli_error($watchlist_table));
}
if (mysqli_num_rows($watchlist_table) > 0) {
//get rows from content table
$contentsTable = mysqli_query($conn, "SELECT * FROM contests WHERE id='$contest_id'")
or die("Error: " . mysqli_error($conn));
//to can use the rows in users table
$row_contents = mysqli_fetch_array($contentsTable, MYSQLI_ASSOC);
//get rows from users table
$userTable = mysqli_query($conn, "SELECT * FROM users WHERE id!='" . $dcs_user->user['id'] . "'")
or die("Error: " . mysqli_error($conn));
require 'vendor/vendor/phpmailer/phpmailer/PHPMailerAutoload.php';
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->SMTPAuth = true;
//$mail->SMTPDebug=2;
//$mail->Debugoutput = 'html';
$mail->SMTPOptions =
[
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
],
];
$mail->Host = 'smtp.gmail.com';
$mail->Username = 'faresalkhwaja#gmail.com';
$mail->Password = 'elkhawajah1';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
//to select all the email in database
while ($row_user = mysqli_fetch_array($userTable, MYSQLI_ASSOC)) {
$mail->From = 'tasqat';
$mail->FromName = 'tasqat';
$mail->addReplyTo('faresalkhwaja#gmail.com', 'tasqat');
$mail->addAddress($row_user['email'], $row_user['email']);
$mail->Subject = "new comment";
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$mail->Body = "job title :" . $row_contents['title'] . "<br>" . "user name :" . $row_comment['display_name'] . "<br>" . "date : " . $row_comment['date'] . "<br>" . "comment : " . $row_comment['comment'] . "<br>" . "host : " . $actual_link;
$mail->AltBody = 'this is body';
}
}//end while loop
Your hosting provider likely has disabled emailing to prevent its system being used for spamming. You should contact them to see if they will enable it for you.
If they will not, you may want to consider using a third-party service.

phpmailer with mysql results

I'm trying to use phpmailer to send out emails to each email address found in the database, but as a unique email. For some reason, it's sending duplicate emails, and it sends it out in as many copies as my query returns rows. So, if my query returns 5 rows, each recipient will receive 5 email (total emails sent is 25). I can't use the same email for multiple recipients because the email content is personalized.
What am I doing wrong with my code? Please help...
Here's my code:
$customers_query = "SELECT customer_name, customer_email, customer_id FROM customers";
$customers = mysql_query($customers_query);
if (!$customers) {
$message = 'Error notice: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
require_once('class.phpmailer.php');
// create an instance
while ($row = mysql_fetch_array($customers)) {
$email = $row['customer_email'];
$name = $row['customers_name'];
$id = $row['customer_id'];
$mail = new PHPMailer();
// use sendmail for the mailer
$mail->IsSendmail();
$mail->SingleTo = true;
$mail->IsHTML(true);
$mail->From = "noreply#domain.com";
$mail->FromName = "MyWebsite";
$mail->Subject = "Welcome to MyWebsite";
$mail->AddAddress($email);
$mail->Body = "Dear ".$name.", welcome to MyWebsite. Your ID is: ".$id.". Enjoy your stay.";
$mail->Send();
}
So, what am missing here? Why does it send that many emails?
Try this:
$mail->ClearAddresses(); after $mail->Send();
Try something like is below, you need to be counting your rows somehow so that it doesn't re-process them. Also, the AddAddress(); function is used to keep adding email addresses to the TO: field, so you need to call ClearAddresses(); in order to restart with a fresh set of recipients.
$customers_query = "SELECT customer_name, customer_email, customer_id FROM customers";
$customers = mysql_query($customers_query);
$count = mysql_num_rows($customers);
$result = mysql_fetch_array($customers);
$i = 0;
if (!$customers) {
$message = 'Error notice: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
require_once('class.phpmailer.php');
// create an instance
while ($i < $count) {
$email = mysql_result($result,$i,"customer_email");
$name = mysql_result($result,$i,"customers_name");
$id = mysql_result($result,$i,"customer_id");
$mail = new PHPMailer();
// use sendmail for the mailer
$mail->IsSendmail();
$mail->SingleTo = true;
$mail->IsHTML(true);
$mail->From = "noreply#domain.com";
$mail->FromName = "MyWebsite";
$mail->Subject = "Welcome to MyWebsite";
$mail->AddAddress($email);
$mail->Body = "Dear ".$name.", welcome to MyWebsite. Your ID is: ".$id.". Enjoy your stay.";
$mail->Send();
$mail->ClearAddresses();
$i++;
}
You can do one more thing, add one more extra field in the customer table, like is_email_sent, yes or no. Once sent email you can update specific row using primary key. so it will not send the same email to multiple time..

Email list from sql practices

I have been using the following to get and email people in my database. The problem is now that the database has over 500+ members the script slows down and SHOWS each member email address in TO: field. I tried a suggestion on another site to use BCC instead but I was wondering isn't there a way to alter this to send the emails individually?
$sql = "SELECT * FROM users WHERE system = '101' AND mailing_list = 'yes'";
$result = mysql_query($sql) or die("Unable to execute<br />$sql<br />".mysql_error());
$row = mysql_fetch_array($result);
var_dump($row);
$to .= $row['email'] . "\r\n";
//send email
php's mail() is very inefficient, I suggest using something like phpmailer
from the manual:
Note:
It is worth noting that the mail() function is not suitable for larger
volumes of email in a loop. This function opens and closes an SMTP
socket for each email, which is not very efficient.
For the sending of large amounts of email, see the » PEAR::Mail, and »
PEAR::Mail_Queue packages.
You need to use PHPMailer as it is meant to be used for just this situation. the trouble with mail() is that it opens and closes a connection after each email. You obviously want to open 1 connection, send all your emails (one by one) and close the connection.
Something like below:
require("class.phpmailer.php");
$mail = new phpmailer();
$mail->From = "list#example.com";
$mail->FromName = "List manager";
$mail->Host = "smtp1.example.com;smtp2.example.com";
$mail->Mailer = "smtp";
#MYSQL_CONNECT("localhost","root","password");
#mysql_select_db("my_company");
$query = "SELECT full_name, email, photo FROM employee WHERE id=$id";
$result = #MYSQL_QUERY($query);
while ($row = mysql_fetch_array ($result))
{
// HTML body
$body = "Hello <font size=\"4\">" . $row["full_name"] . "</font>, <p>";
$body .= "<i>Your</i> personal photograph to this message.<p>";
$body .= "Sincerely, <br>";
$body .= "phpmailer List manager";
// Plain text body (for mail clients that cannot read HTML)
$text_body = "Hello " . $row["full_name"] . ", \n\n";
$text_body .= "Your personal photograph to this message.\n\n";
$text_body .= "Sincerely, \n";
$text_body .= "phpmailer List manager";
$mail->Body = $body;
$mail->AltBody = $text_body;
$mail->AddAddress($row["email"], $row["full_name"]);
$mail->AddStringAttachment($row["photo"], "YourPhoto.jpg");
if(!$mail->Send())
echo "There has been a mail error sending to " . $row["email"] . "<br>";
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
}

Categories