How to send email to address fetched from database via php mailer - php

I have made page where the user enters the data & send email.First i want to insert data into db & then trigger mail to registered email id.Till now i was manually typing the email id. What should be done to fetch the email id from database & send it.
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$sname=$_SESSION['usr_name'];
$room = mysqli_real_escape_string($conn, $_POST['txtrname']);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$dept = mysqli_real_escape_string($conn, $_POST['txtdept']);
$purpose = mysqli_real_escape_string($conn, $_POST['txtpurpose']);
$attendee = mysqli_real_escape_string($conn, $_POST['attendee']);
$date = mysqli_real_escape_string($conn, $_POST['txtdate']);
$btime = mysqli_real_escape_string($conn, $_POST['btime']);
$etime = mysqli_real_escape_string($conn, $_POST['etime']);
$sql="INSERT INTO bookingdetails (room,name,department,purpose,attendee,date,starttime,endtime,status_id)VALUES('$room','$name','$dept','$purpose','$attendee','$date','$btime','$etime','2')";
$res = mysqli_query($conn,"SELECT emailid FROM newuser WHERE username='$sname'");
$row = mysqli_fetch_assoc($res);
$to = $row["emailid"];
require('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
$subject = "Bookig Details";
$content = "<b>Hello $name. Your Booking Details are as follow. Room : $room Date : $date Start Time : $btime End Time : $etime</b>";
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "no";
$mail->Port = 26;
$mail->Username = "admin";
$mail->Password = "###";
$mail->Host = "59.68.1.101";
$mail->Mailer = "smtp";
$mail->SetFrom("admin#hitechplast.in", "Admin");
$mail->AddReplyTo("admin#hitechplast.in", "Admin");
$mail->AddAddress($to);
$mail->Subject = $subject;
$mail->WordWrap = 80;
$mail->MsgHTML($content);
$mail->IsHTML(true);
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
if (mysqli_query($conn,$sql))
{
echo "Record added";
}
else
{
die('Error: ' . mysqli_error());
}
?>

I Think the problem is with session start.
You use this peice of session
$sname=$_SESSION['usr_name'];
and you forget to start session
use
session_start();
at the top of your page

$res = mysqli_query($conn,"SELECT emailid FROM newuser WHERE username='$sname'") or die(mysqli_error($conn));
if($res && mysql_num_rows($res)>0)
{
$data = mysql_fetch_assoc($res);
$userEmail = $data['emailid']; // now this is your email id variable for user's email address.
require('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
$subject = "Bookig Details";
$content = "<b>Hello $name. Your Booking Details are as follow. Room : $room Date : $date Start Time : $btime End Time : $etime</b>";
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "no";
$mail->Port = 26;
$mail->Username = "meetingroom.admin";
$mail->Password = "###";
$mail->Host = "59.68.1.101";
$mail->Mailer = "smtp";
$mail->SetFrom("admin#hitechplast.in", "Admin");
$mail->AddReplyTo("admin#hitechplast.in", "Admin");
$mail->AddAddress($userEmail); // you can't pass php variables in single goutes like '$userEmail'.
$mail->Subject = $subject;
$mail->WordWrap = 80;
$mail->MsgHTML($content);
$mail->IsHTML(true);
}
try this. Your changes seem correct. Only you are passing email variable $to in single quotes. Hope it helps.

You need to fetch the assoc array, not the array.
$row = mysqli_fetch_assoc($res);

Related

warning in base64_encode of in phpmailer class

i am using phpmailer to send mail with attachment, which is sending mail with blank attachment and it shows following warning
Warning: base64_encode() expects parameter 1 to be string, object given in D:\xampp\htdocs\contactform\class\class.phpmailer.php on line 1958
i retrieve file from database which is stored as BLOB file
<?php
require 'config.php';
require 'class/class.phpmailer.php';
$message = '';
$errors ='';
$firstName = $lastName = $emailId = $mobileNumber = $add = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
$firstName = $conn->real_escape_string($_POST['fname']);
$lastName = $conn->real_escape_string($_POST['lname']);
$emailId = $conn->real_escape_string($_POST['email']);
$mobileNumber = $conn->real_escape_string($_POST['mobile']);
$add = $conn->real_escape_string($_POST['address']);
$fileName = $conn->real_escape_string($_FILES['myfile']['name']);
$tmp_name = $_FILES['myfile']['tmp_name'];
$name = $_FILES['myfile']['name'];
$size = $_FILES['myfile']['size'];
if(isset($_POST["submit"]))
{
if((isset($_POST['fname'])&& $_POST['fname'] !='' ))
{
$sql = "INSERT INTO form (fname, lname, email,mobile,address,file,filename,created) VALUES('".$firstName."','".$lastName."','".$emailId."', '".$mobileNumber."','".$add."','".$fileName."','".$name."',now())";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else
{
echo "Registered successfully\n ";
}
}
else
{
echo "Please fill Name and Email";
}
$query="select file from form where email='$emailId'";
$result=$conn->query($query) or die('There was an error1 running the query [' . $conn->error . ']');
$result1="resume.pdf";
$encoding='base64';
$type=" application/pdf";
$message ="hi";
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = '587';
$mail->SMTPAuth = true;
$mail->Username = '****';
$mail->Password = '****';
$mail->SMTPSecure = 'tls';
$mail->From = $_POST["email"];
$mail->FromName = $_POST["fname"];
$mail->AddAddress('***');
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->AddStringAttachment($result,$result1,$encoding,$type).
$mail->Subject = 'Applicant Profile';
$mail->Body = $message;
if($mail->Send())
{
$message = '<div class="alert alert-success">Application Successfully Submitted</div>';
}
else
{
$message = '<div class="alert alert-danger">There is an Error</div>';
echo $mail->ErrorInfo;
}
}
print_r($message);
?>
You're getting this error because $result contains a MySQLi result set object (mysqli_result), not a string. You need to extract the field value before you use it. Also PHPMailer will figure out the encoding and content type for you from the filename you provide (in $result1), so you don't need to set them yourself, like this:
$row = $result->fetch_row();
$mail->addStringAttachment($row[0], $result1);
A separate issue is that you're using a very old version of PHPMailer which has security holes and many bugs, and you've based your code on an obsolete example, so get the latest.

how do i send a user message to their mail from phpmailer?

Hi guys, please I'm having problem with my code. I want to accept user
email and verify it from my database then send the user an email using
PHPMailer but it's giving me error, I guess I did some bunch of error
coding here. please how do I go about it? this question might be silly
but I really need assistance from anyone, please. Thanks.
here is what I've tried out.
<?php
require 'PHPMailer/PHPMailerAutoload.php';
$con = mysqli_connect("localhost","root","password007","voting");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$email = mysqli_real_escape_string($con,$_POST['email']);
$sql = "SELECT VotersID,Email,First_name FROM voters WHERE Email = '$email' ";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
$votersID = $row['VotersID'];
$first = $row['First_name'];
if($count == 1) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '******#gmail.com';
$mail->Password = '*******';
$mail->SMTPSecure = 'tls';
$mail->Port = '587';
$mail->From = '*****#gmail.com';
$mail->FromName = 'West End University College';
$mail->addAddress($email, $first);
$mail->addReplyTo('*****#gmail.com', 'West End University College');
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = 'code for login Confirmation';
$mail->Body = 'Hi, your code is:';
$mail->addAttachment($votersID);
}
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
else{
echo "Message sent successfully";
}
}
?>
Errors :
Notice: Undefined variable: mail in
C:\xampp\htdocs\voters\accConfirm.php on line 45 Fatal error: Call to
a member function send() on null in
C:\xampp\htdocs\voters\accConfirm.php on line 45

Insert Query doesn't works

I have made my insert query in the script, but when it starts instead an error like this
Warning: pg_query(): Query failed: ERROR: syntax error at or near ":" LINE 2: Notice: Undefined variable: row in D:\xampp\htdocs\Feedback... ^ in D:\xampp\htdocs\FeedbackALC\user\send_mail.php on line 60
my script :
<?php
session_start();
require 'phpmailer/PHPMailerAutoload.php';
$email = $_POST['email'];
$password = $_POST['password'];
$to_id = $_POST['toid'];
$to_id2 = $_POST['toid2'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = $email;
$mail->Password = $password;
$mail->setFrom('learningCenter#anabatic.com', 'Anabatic Learning Center');
$mail->addReplyTo('learningCenter#anabatic.com', 'Anabatic Learning Center');
$mail->addAddress($to_id);
$mail->Subject = $subject;
$mail->msgHTML($message);
$mail2 = new PHPMailer;
$mail2->isSMTP();
$mail2->Host = 'smtp.gmail.com';
$mail2->Port = 587;
$mail2->SMTPSecure = 'tls';
$mail2->SMTPAuth = true;
$mail2->Username = $email;
$mail2->Password = $password;
$mail2->setFrom('learningCenter#anabatic.com', 'Anabatic Learning Center');
$mail2->addReplyTo('learningCenter#anabatic.com', 'Anabatic Learning Center');
$mail2->addAddress($to_id2);
$mail2->Subject = $subject;
$mail2->msgHTML($message);
if($mail->send()&&$mail2->send()){
echo "Mail berhasil terkirim";
} else {
echo "mail failed send";
$error = "Mailer Error: " . $mail->ErrorInfo;
?>
<script>alert('<?php echo $error ?>');</script>
<?php
}
include "../connect.php";
$training_dtl_id = "(select max(training_dtl_id)+1 from training_dtl)";
$training_mst_id = strip_tags($_POST['id']);
$user_id = $_SESSION['user_id'];
$create_by = $_SESSION['user_name'];
$change_by = $_SESSION['user_name'];
$query = "INSERT into training_dtl values (".$training_dtl_id.",".$training_mst_id.",".$user_id.",now(),".$create_by.",now(),".$change_by.",FALSE)";
$result = pg_query($conn, $query);
?>

Sending a mail in PHP with Linux

I have a program which works perfectly to send a mail in PHP using Windows, but now I want to send it using a cronjob in Linux to execute it everyday. What do I need to do to work in Linux? Do I need to configure the php.ini file, sendmail etc. like I did in Windows?
Here is the program I've used for sending the email.
<?php
ini_set('max_execution_time', 600);
require 'class.phpmailer.php';
$host = ".....";
$user = "....";
$pass = ".....";
$db = "......";
$con1 = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query1 = "select commands.author, users.badge_no
from commands
inner join users
on commands.author=users.username";
$rs1 = pg_query($con1, $query1) or die("Cannot execute query: $query\n");
$query = "SELECT distinct commands_details.delivery_date,commands_details.command_no,commands.author,commands_details.name
FROM commands_details
inner join commands
on commands_details.command_no=cast(commands.id as varchar)";
$rs = pg_query($con1, $query) or die("Cannot execute query: $query\n");
$nume=array();
$mail1=array();
while ($row = pg_fetch_row($rs1)){
$nume[]=$row[0];
$mail1[]=$row[1];
}
$arrlength = count($nume);
$var_data='2016-06-19';
$mail_trimitere=array();
while ($row = pg_fetch_row($rs)) {
if(strpos($row[0], $var_data) !== false){
for($j=0;$j<$arrlength;$j++){
if($row[2]===$nume[$j]){
$mail_trimitere[0]=$mail1[$j];
echo $mail_trimitere[0];
break;
}
}
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->Username = "......";
$mail->Password = "........";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true;
$mail->From = "......";
$mail->FromName = ".......";
$mail->addAddress(".........","robert");
$mail->Subject = "Testing PHPMailer with localhost";
$mail->Body = 'urmeaza sa primiti maine comanda cu numarul '.' '.$row[1].' '.'produs'.' '. $row[3].' '. 'in data de '.' '.$row[0];
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
}
}
pg_close($con1);
?>

How to retrieve more than one data in email?

I have a table named 'laptop' and a column inside the table named 'Lap_War_Expiry'. I need to send an email to user when the warranty of the laptop is going to expire soon. For your information, there is more than one warranty that will expired in a day. But the code below is only send the same data from table 'laptop'. Why is that happened and what I have to add in the code so that the email send will retrieve two or more data from database ?
This is my coding for sending the email :
<?php
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com'; // "ssl://smtp.gmail.com" didn't worked
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
// ======== get database data ==================
$link = mysql_connect("localhost","root","");
$database="master_inventory";
mysql_select_db ($database,$link) OR die ("Could not open $database" );
$query = 'SELECT Lap_PC_Name, Lap_War_Expiry FROM laptop'; //xyz is id of desired user
name.
$result1 = mysql_query($query);
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
}
$mail->Username = "email#gmail.com";
$mail->Password = "somepassword";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true;
$mail->From = "email#gmail.com";
$mail->FromName = "AMS";
$mail->addAddress("emailaddress","AMS");
$mail->Subject = "Notification on warranty expiry";
$mail->Body = "Dear Madam,<br/><br />The licensed for the following PC will expired
in less than one month.<br /><br /> PC Name : ".$Lap_PC_Name. "<br />Date of expired :"
.$Lap_War_Expiry;
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
?>
You need to move everything from below your while loop into it.
EDIT
Change
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
}
to
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
$mail->Username = "email#gmail.com";
$mail->Password = "somepassword";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true;
$mail->From = "email#gmail.com";
$mail->FromName = "AMS";
$mail->addAddress("emailaddress","AMS");
$mail->Subject = "Notification on warranty expiry";
$mail->Body = "Dear Madam,<br/><br />The licensed for the following PC will expired
in less than one month.<br /><br /> PC Name : ".$Lap_PC_Name. "<br />Date of expired :"
.$Lap_War_Expiry;
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
}

Categories