I'm currently trying to set a variable within a while loop equal to different values of an array. I have my select statement setup so that it pulls the information successfully and can be displayed by echoing the relevant classes. However, if I try to set the rows equal to a variable on the second pass it doesn't run and completes the while loop.
$username = "xxx";
$password = "xxx";
$hostname = "xxx";
$database = "xx";
$dbhandle = mysqli_connect($hostname, $username, $password, $database) or die("Unable to connect to MySQL");
$conn = new mysqli($hostname, $username, $password, $database);
$date = "1996-03-12 12:03:00";
$selectcmd = "SELECT starttime, endtime, partner, worklist, serviceloss, servicereference, siteaddress, ticketref FROM work WHERE starttime='$date'";
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
$result = $conn->query($selectcmd);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$body = $row["starttime"].$row["endtime"];
require "mail.php";
}
} else {
echo "No Mail To Send";
}
$conn->close();
mail.php is the PHPMailer function and sends emails fine.
I know the issue is that I'm trying to set a variable within the while loop. However, I'm not sure how to overcome this. I've attempted to unset the body at the end of the while loop.
mail.php for those who asked:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';
$mail = new PHPMailer();
try {
$mail->isSMTP();
$mail->Host = 'localhost';
$mail->SMTPAuth = false;
$mail->Username = 'user#example.com';
$mail->Password = 'secret';
$mail->Port = 25;
$mail->setFrom('test#test.com', 'test');
$mail->addAddress('joe#example.net');
$date = "today";
$mail->isHTML(true);
$mail->Subject = 'Important Notification';
$mail->Body = $body;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
die();
} catch (Exception $e) {
die();
}
My issue was as #PatrickQ advised.
The die() function was causing the script to stop running altogether. I removed this from mail.php and then moved the require 'mail.php' to outside the while loop. I then added the $mail->send(); function to the while loop.
Everything is as I wish :)
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 months ago.
I am using a select statement to pull data from my DB using a where clause and limited to 1, then i am trying to put the addresses it has pulled into the sendto field on phpmailer.
I have updated the question so the full code is here, i am still unable to pull up the echo from the var that i entered to collect the emails from the list.
<?php
$servername = "localhost";
$username = "####";
$password = "####";
$dbname = "####";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT email FROM emails WHERE status = 'new' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["email"]. " ";
}
} else {
echo "0 results";
}
$sql = "UPDATE emails SET status='done' WHERE status = 'new' LIMIT 1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$var_email = $row["email"];
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';
Class SendMail{
function send(){
$mail = new PHPMailer(true);
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = '####'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = '####'; //SMTP username
$mail->Password = '####';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mail->Port = 465;
//Recipients
$mail->setFrom('info#####', '####');
$mail->addAddress($var_email);
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = '####';
$mail->Body = "####";
$mail->send();
echo 'Message has been sent';
}
}
$sendMail = new SendMail();
$sendMail->send();
$conn->close();
?>
I am hoping its a simple fix, but i feel like somewhere i have put the wrong string which is not allowing me to echo the results into the address field.
any suggestions?
take a variable and assign value to it
ex. $var_email = $row["email"];
$mail->addAddress($var_email);
try it it's working. problem is occur because of php version
I'm trying to send an email with the help of PHPMailer, everything works fine except now I want to have a copy of the send mail in Sent Items.
The website is currently hosted in Bluehost. I tried following the example of PHPMailer - GMail but I'm stuck on which path should I specify.
From the example of PHPMailer - GMail the path for Sent Items is:
{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail
I don't know what path should I specify. Everything works fine in my code, only the path for the sent item is missing.
<?php
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
$username = 'john#mydomain.com';
$password = 'password';
function save_mail( $mail ) {
//path or folder for sent items
$path = "{imap.mydomain.com:993/imap/ssl}[...]/..."; //what exactly is the path for my sent item.
//Tell your server to open an IMAP connection using the same username and password as you used for SMTP
$imapStream = imap_open( $path, $mail->Username, $mail->Password );
$result = imap_append( $imapStream, $path, $mail->getSentMIMEMessage() );
imap_close( $imapStream );
return $result;
}
function send(){
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->Host = 'mail.mydomain.com';
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->SMTPAuth = true;
$mail->Username = $username;
$mail->Password = $password;
$mail->setFrom( $username, 'John Doe' );
$mail->addAddress( 'someone#example.com', 'David Doe' );
$mail->Subject = 'TEST SUBJECT';
$mail->msgHTML('<b>TEST</b>');
$mail->AltBody = 'TEST';
if ( !$mail->send() ) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
if (save_mail($mail)) {
echo "Message saved!";
}
}
}
?>
Thanks to Max for the idea of imap_list function.
This gives me the list of a path for my mail directories.
$host = '{imap.mydomain.com/ssl/novalidate-cert}';
$mail = 'support#mydomain.com';
$pass = 'password';
$mbox = imap_open($host, $mail, $pass, OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$list = imap_list($mbox, $host, "*");
if (is_array($list)) {
foreach ($list as $val) {
echo imap_utf7_decode($val) . "\n";
}
} else {
echo "imap_list failed: " . imap_last_error() . "\n";
}
imap_close($mbox);
?>
using the {imap.mydomain.com} or {imap.mydomain.com:993/imap/ssl}gives me an error of:
can't connect: Certificate failure for imap.mydomain.com: Server
name does not match certificate: /OU=Domain Control
Validated/OU=Hosted by BlueHost.Com, INC/OU=PositiveSSL
Wildcard/CN=*.bluehost.com
Certificate issue, luckily I found this question and I end up using the following host:
{imap.mydomain.com/ssl/novalidate-cert}
and the path I'm looking to forward the sent mail into sent items is:
{imap.mydomain.com/ssl/novalidate-cert}INBOX.Sent
I'm stuck on how to uses PHPMailer. I create a simple PHP form to book a meeting room. Admin needs to log in the system and key in all details including requester email's, factory and room. After admin click 'submit', it will save to database under table 'booking'.
Now, What I want is when I clicked the submit button, It also sent an email to the user about the details that already booked.
Below is my current code:
home.php
<?php
require_once 'configPDO.php';
session_start();
if(!ISSET($_SESSION['login_user'])){
header('location:index.php');
}
$Email = $_SESSION['login_user'];
$sql = $conn->prepare("SELECT * FROM staff WHERE Email='$Email'");
$sql->execute();
$fetch = $sql->fetch();
if(ISSET($_POST['submit'])){
if($_POST['Requested_by'] != "" || $_POST['Factory'] != "" || $_POST['Room'] != ""){
try{
$Requested_by = $_POST['Requested_by'];
$Factory = $_POST['Factory'];
$Room = $_POST['Room'];
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `booking` VALUES ('', '$Requested_by', '$Factory', '$Room')";
$conn->exec($sql);
}catch(PDOException $e){
echo $e->getMessage();
}
$conn = null;
header('location:index.php');
}else{
echo "
<script>alert('Please fill up the required field!')</script>
<script>window.location = 'registration.php'</script>
";
}
}
?>
sendmail.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/Mailer/Exception.php';
require 'PHPMailer/Mailer/PHPMailer.php';
require 'PHPMailer/Mailer/SMTP.php';
require_once 'configPDO.php';
session_start();
$sendermail = '';
$sendername = '';
$senderpassword = '';
$receiveremail = '';
$receivername = '';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.office365.com'; //gmail SMTP server
$mail->SMTPAuth = true;
$mail->Username = $sendermail; //username
$mail->Password = $senderpassword; //password
$mail->SMTPSecure = 'TLS';
$mail->Port = 587; //smtp port
$mail->setFrom($sendermail, $sendername);
$mail->addAddress($receiveremail, $receivername);
$mail->isHTML(true);
$mail->Subject = 'E-booking';
$mail->Body = '<h3>Dear '.$receivername.',</h3>';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: '. $mail->ErrorInfo;
}
?>
Please help me. thanks
I am using phpmailer to send bulk emails to my subscribers but I am facing a terrible problem that is when I send emails to my subscribers, each subscriber is getting the same email more than once. some are getting 4 times and some are getting 14 times.
I am fetching subscriber emails where flag = 0 through Mysql table and at the end of the while loop I am updating subscriber flag to 1. I know its a issue of loop but I don't know where I am doing wrong or even not sure should I used while loop or something else to fix this issue. Any help would be highly grateful to me.
here is my code:
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$link= mysqli_connect("$db_host","$db_username","$db_pass", "mydb") or die ("could not connect to mysql");
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Simply:
//Load Composer's autoloader
require 'vendor/autoload.php';
if(isset($_POST['send'])){
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
$query = "select customer_id, customer_name, customer_email from subscribers where flag_email = 0";
$result = mysqli_query($link, $query) or die("No customer in the table");;
while($values = mysqli_fetch_array($result)){
$id = $values['customer_id'];
$name = $values['customer_name'];
$toemail = $values['customer_email'];
//Server settings
$mail->SMTPDebug = 1; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp server'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('username', 'username');
$mail->addReplyTo('myemail', 'name');
$mail->addBCC(''.$toemail.'', ''.$name.'');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'Here is the message';
$mail->send();
echo 'Message has been sent';
$upd_query = "update subscribers set flag_email = 1 where customer_id = ".$id."";
$result= mysqli_query($link, $upd_query);
}
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
}
This is happening because you're not clearing the to addresses each time around your loop - notice the method is called addAddress, not setAddress, and it does what that suggests. You need to call $mail->clearAddresses(); at the end of your loop to reset it. You're doing things mostly right otherwise, but there are a few things you can do to improve efficiency, mainly using keep alive and setting all the properties that are common to all messages before your loop.
You can see all this working in the mailing list example provided with PHPMailer.
The issue i'm seeing is, the replacement of result variable with update output inside while loop. Please use different variable name inside while loop
$upd_query = "update subscribers set flag_email = 1 where customer_id = ".$id."";
$updateResult= mysqli_query($link, $upd_query);
mailer object creation can be move inside to while loop
$query = "select customer_id, customer_name, customer_email from subscribers where flag_email = 0";
$result = mysqli_query($link, $query) or die("No customer in the table");;
while($values = mysqli_fetch_assoc($result)){
$mail = new PHPMailer(true);
....
}
My website has a create account form, in which it inserts into a database and sends an email and verifies on my AWS SES server. But for some reason my code keeps freezing. If I put an echo "Testing" right above //include_phpmailer, "Testing" will not show up.
<?php
//include phpmailer
require_once('class.phpmailer.php');
require_once('ses.php');
$username = "scapXXXXXX";
$password = "baXXXXXXXX";
$hostname = "db4free.net:3306/scapterlogin";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Could Not establish connection!" . mysql_error());
$dbselect = mysql_select_db("scapterlogin", $dbhandle);
$myusername = $_POST['user'];
$mypassword = $_POST['pass'];
$myemail = $_POST['email'];
$query = "INSERT INTO userInfo (Username, Password, Email, activation_code) VALUES('$myusername', '$mypassword', '$myemail')";
$myquery = mysql_query($query);
if ($myquery) {
//verify email address using SES
$verify = new SimpleEmailService("access_key", "secret_key");
$verify->verifyEmailAddress($myemail));
//SMTP Settings
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "email-smtp.us-west-2.amazonaws.com";
$mail->Username = "AKIAXXXXXXXXX";
$mail->Password = "AoDRf8NBXXXXXXXXXXX";
//
$mail->SetFrom('webmaster#scapter.org', 'The Scapter Team'); //from (verified email address)
$mail->Subject = "New Account"; //subject
//message
$body = 'Dear " . $myusername . ", \r\n Welcome to Scapter! We hope you enjoy all of our products. We have got an account request from this email.
If you did not create an account, you can safely ignore this email.';
$body = eregi_replace("[\]",'',$body);
$mail->MsgHTML($body);
//
//recipient
$mail->AddAddress($myemail, $myusername);
//Success
if ($mail->Send()) {
//setcookie('loggedin', $myusername, Time()+3600);
//header('Location: login.php');
}
//Error
if(!$mail->Send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>
There are couple of unusual factors in your code..
$hostname for db connection does not seem to be a valid one (db4free.net:3306/scapterlogin). If you have an IP address of the db server, you should use that instead.
Using
if ($mail->Send()) {}
and
if(!$mail->Send()) {}
effectively calls the same method twice you should replace 2nd occurrence with a simple else condition.
Using 'die' before $mail->Send() or $myquery = mysql_query($query); can help you identify whether the specific block of code is causing trouble.
You say if you echo on the first line, it will not show up, which leads me to believe that the file is not being loaded, and maybe you have error display turned off, so it's not giving you an error? Check your logs for errors - maybe you are not loading this file with the correct name or you have permissions set so that your server doesn't want to run it.