I'm trying to save multiple tasks and send multiple emails for each user. My code is shortly like this:
<?php
//Save All
foreach($_POST['decode'] as $dcode){
$sec = mysql_query("SELECT owner,mcode FROM members WHERE mcode='$dcode' ORDER BY id ASC");
while($list = mysql_fetch_array($sec)){$mcode=$list[mcode];$owner=$list[owner];}
if (mysql_query ("INSERT INTO tasks (tcode,adder,tdt,title,mcode,subject)
values ('$tcode','$adder','$tdt','$title','$mcode','$subject')")){
echo $owner.' done.<br>';header ("refresh: 5; url=members.php");
//Send info
include("scripts/class.phpmailer.php");
//To who
$sec = mysql_query("SELECT name,em FROM members WHERE mcode='$mcode' ORDER BY id ASC");
while($list = mysql_fetch_array($sec)){$name = $list[name];$em = $list[em];}
//Sender
$sec = mysql_query("SELECT owner FROM members WHERE mcode='$owner' ORDER BY id ASC");
while($list = mysql_fetch_array($sec)){$owner = $list[owner];}
$mail= new PHPMailer();
$mail->AddAddress($em , $name);
$mail->Subject=$owner."has send mail";
$mail->Body="content";
$mail->IsSMTP();
$mail->Host="host.host.com";
$mail->SMTPAuth=true;
$mail->Username="username";
$mail->Password="pass";
$mail->IsHTML(true);
$mail->From="sendermail";
$mail->FromName="Sender";
$mail->Port="587";
$done=$mail->Send();
// Check Mail
if(!$done){echo "Error! Mail not send";}else{echo "Mail send";}
}else{echo "Not Saved";}
}//Save All
?>
It saves the tasks. And sends a single mail. But i cant send multiple emails for each task.
Phpmailer sends error: Cannot declare class
I've tried this way for that error:
if(class_exists('PHPMailer') != true){$mail= new PHPMailer();}
And it says Call to a member function AddAddress()
And ive tried this way:
$mail->ClearAddresses();
And i think im putting the codes to wrong areas. Can u please help me to fix this.
I've searched "stack" and tried a few methods also. But they doesnt work on mine.
I think thats about the foreach command.
//Sender
$sec = mysql_query("SELECT owner FROM members WHERE mcode='$owner' ORDER BY id ASC");
while($list = mysql_fetch_array($sec))
{
$owner = $list[owner];
}
$mail= new PHPMailer();
$mail->Body="content";
$mail->Subject=$owner."has send mail";
$mail->IsSMTP();
$mail->Host="host.host.com";
$mail->SMTPAuth=true;
$mail->Username="username";
$mail->Password="pass";
$mail->IsHTML(true);
$mail->From="sendermail";
$mail->FromName="Sender";
$mail->Port="587";
//To who
$sec = mysql_query("SELECT name,em FROM members WHERE mcode='$mcode' ORDER BY id ASC");
while($list = mysql_fetch_assoc($sec))
{
$email = $list['em'];
$mail->ClearAddresses();
$mail->AddAddress($email);
$mail->Send();
}
Related
I'm setting a phpmailer service in which I'm just sending a link access to some users. The service works perfectly. My problem comes out when I set a IF statement and it doesn't validate. I just want that it can enter to the if validation. The validation to make is when, $result=='s' is true, send the mail, else ($result=='n'), do nothing.
I've researched a lot about this error, obviously not solution found.
This is for a mobile app built in ionic 3 with TypeScript and PHP services in Apache server. Also I use a connection to a MySQL DB.
{
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
include('conecction.php');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpMailer/src/Exception.php';
require 'phpMailer/src/PHPMailer.php';
require 'phpMailer/src/SMTP.php';
$id =$request->id;
$counting = count($request->people);
for($i=0;$i<$counting ;$i++){
$name=$request->people[$i]->name;
$email=$request->people[$i]->mail;
$hash=md5($id.$email);
$sql="select assisted from assistance where mail= '$email' and idmeeting = '$id'";
$result = $conn->query($sql);
if($result == 's'){
$mail = new PHPMailer;
$mail->SMTPDebug = 4;
$mail->setFrom('noresponder#Prueba.com', 'Prueba MeetCoomeva');
$mail->addAddress($email, $name);
$mail->Subject = 'Subject';
$mail->Body = "Message Body "
}
if ($mail->send()) {
$response['message']="Sent.";
} else {
echo "Sending error: " . $mail->ErrorInfo;
}
}
echo json_encode($response);
?>
}
I want the service compose and send the mail when it have made the validation $result=='s'
I getting a 500 server internal error just by this. I just want it sends the mail when the validation is true or do nothing when entered in else.
This isn't enough:
$sql="select assisted from assistance where mail= '$email' and idmeeting = '$id'";
$result = $conn->query($sql);
if($result == 's'){
$result contains an instance of mysqli_result, not a simple string, so comparing it with s will never match. You need to fetch the row from the result set first, like this:
$sql="select assisted from assistance where mail= '$email' and idmeeting = '$id'";
$result = $conn->query($sql);
$row = $result->fetch_row();
if($row[0] == 's'){
I am using a PHP Script written by me with AWS (Amazon Web Service) PHP Script to send emails using SMTP
Everytime I run this script, say I have 3 user's in my database, then the first user get's mail of the first, second and third person. The second user get's mail to second and third person. And the third user get's the mail to the third person only.
I don't know why this is happening, and been pulling my hair for some time. Maybe I am missing some point, that is why adding a question here.
Pre-Requisites:
func1() = Is used to get emails from DB whom I have not send Emails Yet, return's a single value (ID) only
func2() = Is used to get the data of that particular user whose ID was found in func1()
func3() = Is used to mark "Send" to that particular ID whom we send the mail.
<?php
require 'aws-autoloader.php';
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->setFrom('myemail#address.com', 'My Company Name');
$mail->Username = 'Username';
$mail->Password = 'Password';
$mail->Host = 'email-smtp.us-west-2.amazonaws.com';
class Db {
public function dbconnect(){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
public function func1()
{
$conn=$this->dbconnect();
$stmt = $conn->prepare("CALL func1()");
$stmt->execute();
$result=NULL;
$result = $stmt->get_result();
$item=NULL;
while ($row = $result->fetch_array(MYSQLI_NUM))
{
$item[] = $row;
}
return $item;
$stmt->close();
$conn->close();
}
public function func2($id)
{
$conn=$this->dbconnect();
$stmt = $conn->prepare("CALL func2(?)");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$item=NULL;
while ($row = $result->fetch_array(MYSQLI_NUM))
{
$item[] = $row;
}
return $item;
$stmt->close();
$conn->close();
}
public function func3($id)
{
$conn=$this->dbconnect();
$stmt = $conn->prepare("CALL func3(?)");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$item=NULL;
while ($row = $result->fetch_array(MYSQLI_NUM))
{
$item[] = $row;
}
return $item;
$stmt->close();
$conn->close();
}
}
$count=0;
$obj=new Db;
$ids=$obj->func1();
while(($ids[0][0]!=0)&&($count<1000)){
$ids=$obj->func1();
$rslt=$obj->func2($ids[0][0]);
if($rslt[0][0]!=NULL)
{
$idno=$rslt[0][0];
$companyname=$rslt[0][2];
$email=$rslt[0][16];
$complete=NULL;
do{
$mail->addAddress($email, $companyname);
$mail->Subject = 'My Subject';
$mail->Body = '<p>Hello</p>';
$mail->AltBody = "Hello";
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->isHTML(true);
if(!$mail->send()) {
echo "Email not sent. " , $mail->ErrorInfo , PHP_EOL;
} else {
$complete=$obj->func3($ids[0][0]);
}
}while($complete[0][0]!=3);
}
$count=$count+1;
//if($count%10==0) Trying to give a small break after each 10 emails are send
sleep(1);
}
$count=$count-1;
echo 'Email Send to: '.$count.' Users.<br>';
?>
After the function is called, I receive emails as described at the start. And all the users are marked "Send"
Any Idea what I may be doing wrong to get result like that.
Your code is using the same PHPMailer object for each email, and it is adding addresses using $mail->addAddress() without resetting the list of email addresses between emails hence the list of recipients is growing each time.
You can call $mail->clearAllRecipients() for each new email or you could create a new PHPMailer object for each email. Note that if you choose the former approach then you should check to see if there are any other things that also need to be reset from one email to the next.
So a couple of months ago i worked on my registration form with an com code (that is being send through the email) to activate it. The case is that the registration, and the activation of it always worked. But since recently, after some changes, it suddenly wont work anymore. The registration works,the email is being send to me with the com code link, and it also says i can now log in, but as soon as i try to log in with the made account, it sends me to my login error (wrong password or email). As soon as i look in my databse i also see that the data hasnt been inserted (its empty). Ive looked and done multiple things trying to get it fixed but none of it is working. So my last resort: stack;) The code is posted below (left the form code out btw since i dont think that is giving the problem):
The code for connection to the databse is (which is included everywhere):
<?php
$user = "XX";
$host = "XX";
$password = "XX"; //http://www.codinghorror.com/blog/2007/09/youre-probably-storing-passwords-incorrectly.html //
$database = "XX";
$conn = new mysqli($host, $user, $password, $database)or die ("Error message");
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
?>
After entering the register button this is the register checking page:
session_start();
include('configdb.php');
if(isset($_SESSION['error']))
{
header("Location: indexresp.php");
exit;
}
else{
if (isset($_POST["submit"])){
$register = $_POST['submit'];
$email2 = strip_tags($_POST['email']);
mysqli_select_db($conn, $database);
$emailcheck = mysqli_query($conn, "SELECT email from user WHERE email='$email2'");
$check = mysqli_num_rows($emailcheck);
if ($check == 0){
}
else {
$_SESSION['error']['email'] = "This Email is already used.";
header("Location: indexresp.php");
exit;
}
}
// the register (form field) data:
$voornaam = $_POST['voornaam'];
$achternaam = $_POST['achternaam'];
$email = $_POST['email'];
$password = $_POST['wachtwoord'];
$com_code = md5(uniqid(rand()));
$sql2 = "INSERT INTO user (email, password, com_code, voornaam, achternaam) VALUES ('$email', '$password', '$com_code', '$voornaam', '$achternaam')";
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP(); // set mailer to use SMTP
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Port = XXX;
$mail->Username = "XXXXX"; // SMTP username
$mail->Password = "XXX"; // SMTP password
$mail->SetLanguage("nl");
$mail->From = "XXXXX";
$mail->FromName = "Oblectare";
$mail->AddAddress("$email");
// name is optional
$mail->AddReplyTo("XXXXX", "Information");
$mail->WordWrap = 50; // set word wrap to 50 characters
//$mail->AddAttachment("/var/tmp/file.tar.gz"); // add attachments
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional name
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Account registratie";
$mail->Body = "http://localhost/debasis/hoofdstuk03/confirm.php?passkey=$com_code <br>This adress needs to be copyed in the browser and this is your password:<br><br>" .$password;
$mail->AltBody = "http://localhost/debasis/hoofdstuk03/confirm.php?passkey=$com_code. This adress needs to be copyed in the browser and this is your password:" .$password;
if(!$mail->Send())
{
echo "Error mail<p>";
echo "Mail Error: " . $mail->ErrorInfo;
exit;
}
include ('mailconfirmation.php'); // text to say the email has been send
}
So this code sends an email with the activation code (com code). The code for the email confirmation is just plain text so i left it out.
The next being done is setting the activation (with the supplied link) to yes. This is the code that does that:
include('configdb.php');
$passkey = $_GET['passkey'];
$sql = "UPDATE user SET com_code=NULL WHERE com_code='$passkey'";
$result = mysqli_query($conn,$sql) or die(mysqli_error());
if($result)
{
echo '<div>Your account is now active. You may now Log in</div>';
}
else
{
echo "Some error occur.";
}
?>
So when it passes the if (connection) the user gets redirected to the index where he can login with his account info and his info should be activated (by the update). I think the problem is in this piece of code as the sql variable in here doesnt update the com_code anymore for some reason.
After the redirection i try to login with the just inputted (and as it should be: the activated) details.
The code that checks the login (which look if the pass and mail are valid) is as follows:
session_start();
include('configdb.php');
if(isset($_POST['submit_login']))
{
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$result = mysqli_query($conn,"SELECT * FROM user WHERE email='$email' AND password='$password' AND com_code IS NULL"); // was password
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 )
{
$_SESSION['email']=$row['email'];
header("Location: member.php");
exit;
}
else
{
include ('errorlogin.php');
}
}
I hope one of you guys can help me with this problem cause after 2 hours searching it is (for now) enough for me;)
Sorry for my english and some dutch words in the code (try'd to translate some).
Thx in advance!
Your insert part :
$sql2 = "INSERT INTO user ..."
Is never used in the provided code. Maybe you removed the SQL process by error.
I'm trying to send an (up to 4) attachments using PHPMailer. The files are on my server.
This is how my script works:
User sees a job or resume and contacts them by using the contact form. The contact form stores the data along with the attachments on the server. We will then review the message filtering out spams/scams. If the message is genuine then we will send the message through.
I have the information stored on the server and Im able to send that information via email however the attachments are not sending.
Here is the code used to send the mail:
if ($_GET['status'] == 'approve') {
$id = $_GET['id'];
dbconnect($dbuser, $dbpass, $db);
$sql = "SELECT * FROM $db.mail WHERE id = $id";
$results=mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
$id = $row["id"];
$to = $row["to"];
$from = $row["from"];
$subject = $row["subject"];
$message = $row["message"];
$file1 = $row["file1"];
$file2 = $row["file2"];
$file3 = $row["file3"];
$file4 = $row["file4"];
$result = mysql_query("UPDATE mail SET `status` = '1', `approvedtime` = NOW() WHERE id = " . $_GET['id'])
or die(mysql_error());
header("Location: mail.php");
// PHPMailer - Start
$email = new PHPMailer();
$email->setLanguage('ja');
$email->From = $from;
$email->FromName = 'MySite.com';
$email->Subject = $subject;
$email->Body = $message;
$email->addAddress($to);
if (!empty($file1)) {
$file1 = 'upload/'.$file1;
$email->AddAttachment($file1);
}
if (!empty($file2)) {
$file2 = 'upload/'.$file2;
$email->AddAttachment($file2);
}
if (!empty($file3)) {
$file3 = 'upload/'.$file3;
$email->AddAttachment($file3);
}
if (!empty($file4)) {
$file4 = 'upload/'.$file4;
$email->AddAttachment($file4);
}
return $email->Send();
// PHPMailer - Start
}
} elseif ($_GET['status'] == 'reject') {
dbconnect($dbuser, $dbpass, $db);
$result = mysql_query("UPDATE mail SET `status` = '2', `approvedtime` = NOW() WHERE id = " . $_GET['id'])
or die(mysql_error());
header("Location: mail.php");
}
Why are the attachments not sending? Am I missing a step in my code or have something incorrect?
Thanks for the help!
I am a bit confused about how to use foreach. I read some internet things on it and I kind of understand how it works, but I don't fully understand it. I think I could use foreach to create a PHP mass emailer that sends blank carbon copy to email addresses and adresses the customer by name in the subject (Dear, Michael Here is your email). I've figured out how to retrieve the names and emails from my database into variables and I know how to email, but I don't know how to send multiple emails at once and to associate the name and email address.
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "MichaelBerna.db.10339998.hostedresource.com";
$username = "MichaelBerna";
$dbname = "MichaelBerna";
//These variable values need to be changed by you before deploying
$password = "********";
$usertable = "subscribers";
$yourfield = "name";
$yourfield1 = "email";
//Connecting to your database
$link = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result)
{
while($row = mysql_fetch_array($result))
{
$name = $row["$yourfield"];
$email = $row["$yourfield1"];
echo "Name: $name<br>";
echo "Email: $email<br>";
//mysqli_free_result($result);
//mysqli_close($link);
}
}
?>
Here is my email code:
<?php
require_once '../PHPMailer_5.2.2/class.phpmailer.php';
$name = $_POST['name'] ;
$email = $_POST['email'] ;
//$file = $_POST['file'] ; // I'm going to later add a file later to be attached in email from database
$body = "Hey $name thank you for continuing to be a valued customer! This month's story is included in this email asa an attachment.";
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try
{
$mail->AddAddress($email, $name);
$mail->SetFrom('admins_email#yahoo.com', 'Site Admin');
$mail->AddReplyTo('admins_email#yahoo.com', 'Site Admin');
$mail->Subject = "Dear $name Your monthly subscription has arrived!";
$mail->Body = $body;
if ($_FILES['file']['size'])
{
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);// attachment
}
$mail->Send();
echo "Email Sent Successfully</p>\n";
}
catch (phpmailerException $e)
{
echo $e->errorMessage(); //Pretty error messages from PHPMailer
}
catch (Exception $e)
{
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Basically, I need a way to combine these two scripts and link them together and that's what I'm unsure of how to do.
Put the mailing code in a function, e.g. send_mail(), so that it can be called from different places. Then change your database query loop to:
while ($row = mysql_fetch_assoc($result)) {
send_mail($row['name'], $row['email'), "Text of the email");
}