I am testing a form that asks for a users email and then sends him his name,surname and cellphone number. Now everything is working. It selects the user depending on the email entered. It sends the email.
The only issue I am having is how do I insert the data from the table into the email thats sending to him?
Eg.$mail->Body = "Your company details are: " Name,Surname,Cellphone;
thats the issue I am currently facing. My full code is below.
I am still quite new at PHP so if this is a general/common error, then I apologise.
<?php
error_reporting(1);
ini_set('error_reporting', E_ALL);
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="****"; // Mysql password
$db_name="Username"; // Database name
$tbl_name="Name"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password, $db_name);
// Define $username and $password
$username=$_POST['user_name'];
$sql="SELECT * FROM $tbl_name WHERE Name='$username'";
$result=mysqli_query($conn, $sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if ($count > 0)
{
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "****"; // SMTP server // enables SMTP debug information
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "****"; // sets the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "****"; // SMTP account username
$mail->Password = "****"; // SMTP account password
$mail->From = "Test";
$mail->FromName = "Test";
$mail->AddAddress($username, "");
$mail->isHTML(true);
$mail->Subject = 'Out Of Office Password';
$mail->Body = "Your Out Of Office password: ";
if(!$mail->Send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit();
}
else
{
echo 'Email Sent Successfully!';
}
}
?>
The form:
<center>
<html>
<head>
<title>User Information</title>
</head>
<body>
<form action="check-user.php" method="POST">
<h3>User Information</h3>
Email: <input type="text" name="user_name"><br>
<input type="submit" name="submit" value="Send Info">
</form>
</body>
</html>
</center>
First make your connection valid
$conn = mysqli_connect($host, $username, $password, $db_name)
// if u get connection valid message delete this if statement this is just for testing your connection
if ($conn) {
echo 'connection valid';
} else {
echo 'connection invalid ' . mysqli_error($conn);
}
And u don't need this
echo "Connected to MySQL<br />";
mysqli_select_db("$db_name") or die(mysqli_error());
echo "Connected to Database<br />";
Change this line
$result=mysqli_query($conn, $sql);
And this one
if ($count > 0) {
And because u new to php, i think u need atleast learn how to connect to database, check for error_reporting, get/update/insert/delete data into database.
And my opinion is if u are starting to learn use PDO with prepared statements because it safe. This mysqli without escaping will get u trouble with security.
EDIT:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="****"; // Mysql password
$db_name="Username"; // Database name
$tbl_name="Name"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password, $db_name) or die(mysqli_error($conn));
if (isset($_POST['submit']))
{
// Define $username
$username = $_POST['user_name'];
$sql = "SELECT * FROM $tbl_name WHERE Name='$username'";
$result = mysqli_query($conn, $sql);
// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);
if ($count > 0 )
{
// get data from user
$data = mysqli_fetch_array($result, MYSQLI_ASSOC);
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "****"; // SMTP server // enables SMTP debug information
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "****"; // sets the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "****"; // SMTP account username
$mail->Password = "****"; // SMTP account password
$mail->From = "Test";
$mail->FromName = "Test";
$mail->AddAddress($username, "");
$mail->isHTML(true);
$mail->Subject = 'Your Company Details';
$mail->Body = "Your company details are: Name: = " . $data['Name'] . ", Surname: " . $data['Surname'] . ", Cellphone: " . $data['Cellphone'];
if(!$mail->Send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit();
}
else
{
echo 'Email Sent Successfully!';
}
}
ob_end_flush();
?>
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 have a delete query below from a php page where the user types in an extension number and the entry is deleted from the database.
Name,Email,Extension,Phone,Department the whole line is deleted by entering the extension number of the database member.
Now I have phpmailer installed and working for this, it is sending a mail to IT#sadsa.com but I am trying to make it also send the mail to another address before the member is deleted from the database depending on the department they are in.
Eg. if they are in Sales department then the email must be sent to sales#sadsa.com and IT#sada.com, if they are in the Admin Department then the mail must be sent to Admin#sadsa.com and IT#asdas.com.
My current code below :
delete.php (the php page where the user enters the extension number to delete)
<?php
require ("database.php");
session_start();
if (!isset($_SESSION['CheckLogin'])) { header("Location: login.php"); }
$this_user_ext =$_REQUEST['extension'];
// sending query
mysql_query("DELETE FROM users WHERE extension = '$this_user_ext'")
or die(mysql_error());
if($_POST['action']) {
include('maildelete.php');
$extension=$_POST['extension'];
header("Location: index.php");
}
?>
<center><form action="" method="post">
Enter 4 Digit Extension Number :<br><input type="text" name="extension"><br><input type="submit" name="action" value="Delete!">
<br> <br>
<h3>
Main Menu
</h3>
</form>
</center>
maildelete.php (this is the script that sends the mail to IT#sad.com)
<?php
$extension = $_POST['extension'];
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.titan-networks.co.za"; // SMTP server // enables SMTP debug information
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.titan-networks.co.za"; // sets the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "jurgen#titan-networks.co.za"; // SMTP account username
$mail->Password = "****"; // SMTP account password
$mail->From = "no-reply#alpinemotors.co.za";
$mail->FromName = "Extension List";
$mail->AddAddress('jurgen#titan-networks.co.za', "");
$mail->isHTML(true);
$mail->Subject = 'Extension Deleted';
$mail->Body = "Extension Number " . $extension . " was removed from the Extension List";
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Email Sent Successfully!';
?>
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);
?>
I'm building a registration form using MySQL to store data and work perfectly. when users register will be sent a verification email to activate user accounts. the problem is not the verification email sent to the email users but user data and the activation code can get into mysql.
Here code for insert.php
<?php
//panggil file config.php untuk menghubung ke server
include('config.php');
//tangkap data dari form
$nama = $_POST['nama'];
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$alamat = $_POST['alamat'];
$telp = $_POST['telp'];
$password = mysql_real_escape_string($_POST['password']);
// regular expression for email check
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/';
if(preg_match($regex, $email))
{
$password=md5($password); // encrypted password
$activation=md5($email.time()); // encrypted email+timestamp
$count=mysql_query("SELECT id_user FROM user WHERE email='$email'");
// email check
if(mysql_num_rows($count) < 1)
{
$query = mysql_query("insert into user (nama,email,telp,password,alamat,username,activation) VALUES('$nama', '$email', '$telp', '$password', '$alamat', '$username', '$activation')") or die(mysql_error());
if ($query)
{
header('location:index.php');
}
// sending email
include ('sendEmail.php');
$to=$email;
$subject="Email verification";
$body='Hi, <br/> <br/> Silakan verifikasi dengan klik link di bawah ini. <br/> <br/> Verifikasi';
sendEmail($to,$subject,$body);
$msg= "Registration successful, please activate email.";
}
else
{
$msg= 'The email is already taken, please try new.';
}
}
else
{
$msg = 'The email you have entered is invalid, please try again.';
}
// HTML Part
//}
?>
and here the code sendEmail.php
<?php
function sendEmail($to,$subject,$body)
{
require ('class.phpmailer.php');
$from = "me#kumistebal.web.id";
$mail = new PHPMailer();
$mail->IsSMTP(true); // use SMTP
$mail->IsHTML(true);
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "ssl://smtp.gmail.com"; // SMTP host
$mail->Port = 465; // set the SMTP port
$mail->Username = "*********#gmail.com"; // SMTP username
$mail->Password = "*********"; // SMTP password
$mail->SetFrom($from, 'From Name');
$mail->AddReplyTo($from,'From Name');
$mail->Subject = $subject;
$mail->MsgHTML($body);
$address = $to;
$mail->AddAddress($email, $to);
if(!$mail->Send())
echo "Mailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
}
?>
Does anyone have any idea how to do?
Instead of $mail->Host = "ssl://smtp.gmail.com"; // SMTP host
just use
$mail->Host = "smtp.gmail.com"; // SMTP host
You need to change host with $mail->Host = "smtp.gmail.com"; // SMTP host and $mail->Port =25; // set the SMTP port
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);