Ok, I'm guessing this is something simple or I'm using something deprecated that I didn't know about.
I'll remove superfluous bits from my code, but everything removed has been tested.
The original code is based on a very common tutorial script that I've seen everywhere. It is getting to the line:
while ($row = $res->fetch_array()) {
and the php is failing with a common: Call to a member function fetch_array() on a non-object.
Normally this would flag to me that my SQL is failing or returning something unwanted, I'd have a minor fix and then move on with my life. However that doesn't appear to be the case. I've been over and over that SQL and it is returning what I want it to.
I thought it might have something to do with calling the while loop inside the else (but that shouldn't be a problem) or that the mail call is within the while loop.
Original Code:
$email = $link->real_escape_string($_POST["web_forgot_email"]);
$sendemail = 0;
$sql = "SQL to return Name and Email (Tested extensively and works)";
$res = $link->query($sql);
if ($res->num_rows == 0) {
$arr = array("web_forgot_success" => "web no account");
echo json_encode($arr);
} else {
while ($row = $res->fetch_array()) {
$sendemail = $row['CLIENT_EMAIL'];
$name = $row['NAME'];
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "localhost";
$mail->SMTPAuth = true;
$mail->Username = "quizzically#quizzically.co.uk";
$mail->Password = "quizzically01";
$mail->From = "quizzically#quizzically.co.uk";
$mail->FromName = "quizzically";
$mail->AddAddress($sendemail);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = "quizzically password reset confirmation";
$mailer = "Email Message";
$mail->Body = $mailer;
if(!$mail->Send()) {
$arr = array("web_forgot_success" => "web no send");
echo json_encode($arr);
} else {
$arr = array("web_forgot_success" => "web forgot success");
echo json_encode($arr);
}
}
}
So I rejigged code so that it finds variables $sendemail and $name first and then send an email but every time (even though the $sendemail variable is not 0) it skips that if statement and returns the else. I've tested the $sendemail variable by sending it back to myself in the else variable and it is definitely not 0.
Good thing is that the PHP does not fail, bad thing is that something is causing the code to skip the whole if section dealing with sending the email.
Rejigged Code:
$email = $link->real_escape_string($_POST["web_forgot_email"]);
$sendemail = 0;
$sql = "SQL to return Name and Email (Tested extensively and works)";
$res = $link->query($sql);
if ($res->num_rows == 0) {
$arr = array("web_forgot_success" => "web no account");
echo json_encode($arr);
}
while ($row = $res->fetch_array()) {
$sendemail = $row['CLIENT_EMAIL'];
$name = $row['NAME'];
}
if ($sendemail != 0) {
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "localhost";
$mail->SMTPAuth = true;
$mail->Username = "quizzically#quizzically.co.uk";
$mail->Password = "quizzically01";
$mail->From = "quizzically#quizzically.co.uk";
$mail->FromName = "quizzically";
$mail->AddAddress($sendemail);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = "quizzically password reset confirmation";
$mailer = "Email Message";
$mail->Body = $mailer;
if(!$mail->Send()) {
$arr = array("web_forgot_success" => "web no send");
echo json_encode($arr);
} else {
$arr = array("web_forgot_success" => "web forgot success");
echo json_encode($arr);
}
} else {
$arr = array("web_forgot_success" => "web forgot failed");
echo json_encode($arr);
}
I'm hoping that I'm doing something deprecated that I haven't found or whatnot, but any help would be appreciated.
The answer is in my own inability to test fully. I had an issue with the html in the message of the email I was sending. This must have been throwing up and error and then the PHP failed on the while loop.
Error in the HTML fixed (it was an un-escaped double quote) and everything is sending fine with no errors.
Related
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.
code:
<?php
include 'library.php';
include "classes/class.phpmailer.php";
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$sql = "select email from login where email='".$email."'";
$results = mysqli_query($con,$sql);
$fetch = mysqli_num_rows($results);
if($fetch > 0)
{
echo "<p id='red'>Email already exist. Please register with different email id.</p>";
}
else
{
$query = "insert into student_login(email)values('$email')";
$result = mysqli_query($con,$query);
if($result==true)
{
$information="hello everyone";
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = 'example.com';
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = 'cpanel-username';
$mail->Password = 'cpanel-password';
$mail->AddReplyTo($email);
$mail->SetFrom("info#example.com", $email);
$mail->Subject = "Account Activation Link #Example";
$mail->AddAddress($email);
$mail->MsgHTML($information);
$send = $mail->Send();
if($send)
{
echo "<p id='green'>To activate your account. Please login your email and click on link.</p>";
}
else
{
echo "<p id='red'>Your message not sent.</p>";
}
}
else
{
echo "<p id='red'>Error!</p>";
}
}
}
?>
In this code I am using smtp mail function to sent an email quickly. But here what happen when I click on submit button. It show me successfull message but can't receive an email. I do't know where am I doing wrong. How can I fix this issue ?Please help me.
Thank You
I think that two things will help you in diagnosing such problems:
Use try-catch syntax. If something is wrong then you can catch this in block
use SMTP Debug for phpmailer
this is example how you can use mailer:
<?php
require('./vendor/autoload.php');
use PHPMailer\PHPMailer\PHPMailer;
class Mailer {
public $phpmailer;
public function __construct($addresses)
{
$this->phpmailer = new PHPMailer(true);
$this->phpmailer->SMTPDebug = 3; // here you can debug
$this->phpmailer->isSMTP();
$this->phpmailer->Host = 'SMTP.host.example.blabla';
$this->phpmailer->SMTPAuth = true;
$this->phpmailer->Port = 587;
$this->phpmailer->Username = 'username';
$this->phpmailer->Password = 'password';
$this->phpmailer->SetFrom('username', 'subject');
$this->phpmailer->CharSet = "UTF-8";
foreach ($addresses as $address) {
$this->phpmailer->AddAddress($address);
}
}
public function send($messageTemplate) {
try {
$this->phpmailer->MsgHTML($messageTemplate);
$this->phpmailer->Subject = 'subject';
$this->phpmailer->Send();
return true;
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
}
}
and use it:
$mail = new Mailer(array('test#test.com'));
if ($mail->send('some message')) {
echo "mail send";
}
omkara
A good idea is take test by parts, so:
First of all, ensure that there are no problems with sending emails, and then check your code!
1 - Can You send a e-mail using the web server (whitout use php)?
2 - Check if mail() function is enabled on your server, here's how to do it.
3 - After try run your code check the php logs in the server.
i made a php function to send mail using phpmailer. but, there is a problem in the function. it neither send mail nor shows error. please help me out. i'm fetching mail body and some other details from other functions and its working fine except it doesn't send mail and i think there must be some problem with the host,port,username,etc.
please help me out.
thanks
my funciton:
public static function sendEmail($data) {
$r_error = 1;
$r_message = "";
$r_data = array();
$q = "select * from config where type='email_detail'";
$r = self::DBrunQuery($q);
$row = self::DBfetchRow($r);
$detail = json_decode($row['value'], true);
include "phpmailer/PHPMailerAutoload.php";
if (!empty($data['email'])) {
foreach ($data as $var) {
$work_email = 'fahadansari12feb#gmail.com'; //$var['email_id'];
$name = 'fahad'; //$var['name'];
$subject = $var['subject'];
$body = $var['body'];
$cc = $var['cc_detail'];
$bcc = $var['bcc_detail'];
$file_upload = $var['upload_file'];
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = '5.9.144.226'; //$detail['host'];
$mail->Port = '2222'; //$detail['port'];
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = 'fahadansari12feb#gmail.com'; //$detail['username']; //sender email address
$mail->Password = 'mypassword'; //$detail['password']; // sender email password
$mail->setFrom('hr#excellencetechnologies.in', 'Excellence Technologies'); // name and email address from which email is send
$mail->addReplyTo('hr#excellencetechnologies.in', 'Excellence Technologies'); // reply email address with name
$mail->addAddress($work_email, $name); // name and address to whome mail is to send
if (sizeof($cc) > 0) {
foreach ($cc as $d) {
$mail->addCC($d[0], $d[1]);
}
}
if (sizeof($bcc) > 0) {
foreach ($bcc as $d2) {
$mail->addBCC($d2[0], $d2[1]);
}
}
$mail->Subject = $subject; // subject of email message
$mail->msgHTML($body); // main message
// $mail->AltBody = 'This is a plain-text message body';
//Attach an image file
if (sizeof($file_upload) > 0) {
foreach ($file_upload as $d3) {
$mail->addAttachment($d3);
}
}
//send the message, check for errors
if (!$mail->send()) {
$row3 = $mail->ErrorInfo;
} else {
$row3 = "Message sent";
}
}
}
if ($row3 != "Message sent") {
$r_error = 1;
$r_message = $row3;
$r_data['message'] = $r_message;
} else {
$r_error = 0;
$r_message = "Message Sent";
$r_data['message'] = $r_message;
}
$return = array();
$return['error'] = $r_error;
$return['data'] = $r_data;
return $return;
}
You've not posted enough info, but I'm going to guess your problem. You're enabling TLS, but you're connecting to an IP address rather than a host name, so your host name will never match the name on the certificate and you will get a TLS validation failure on SMTP connections.
Connect to a named host with a valid certificate, or disable certificate checks (see PHPMailer docs for how to do that), though that's not recommended.
You're also using an old version of PHPMailer, so upgrade.
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
First time posting so any help greatly appreciated...
I'm happy the SQL query works and returns two 2 rows
I'm happy to leave message as "hello" for now
I've looked through many answers and none solve my problem
This function will send the mail to only the first (of 2) recipient but not the second.
If anyone could tell me where I am going wrong I would be very grateful...
public function sendOrderEmail($customer_order_id)
{
$sql3=" SELECT DISTINCT w.user_id AS supplier_id,
s.trading_name AS supplier_name,
s.contact_email AS supplier_email
FROM supplier_info AS s
JOIN wine AS w ON w.user_id = s.id
JOIN order_detail AS o ON o.wine_id = w.id
WHERE o.order_no_id = :customer_order_id ORDER BY supplier_id DESC;";
$query3 = $this->db->prepare($sql3);
$query3->execute(array(':customer_order_id' => intval($customer_order_id)));
//$result3 = $query3->fetchAll();
while($row3 = $query3->fetch(PDO::FETCH_ASSOC)){
// while ($row3 = $query3->fetch()) {
$supplier_name = $row3['supplier_name'];
$supplier_email = $row3['supplier_email'];
// foreach($result3 as $key => $output){
//$supplier_id = $output->supplier_id;
// $supplier_email = $output->email; */
$mail = new PHPMailer;
if (EMAIL_USE_SMTP) {
$mail->IsSMTP();
$mail->SMTPDebug = PHPMAILER_DEBUG_MODE;
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
if (defined('EMAIL_SMTP_ENCRYPTION')) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
} else {
$mail->IsMail();
}
// Build email body
$message = "<p>hello</p>";
// fill mail with data
$mail->isHTML(true);
$mail->From = "billyjlennon#gmail.com";
$mail->FromName = "Me";
$mail->AddAddress($supplier_email);
$mail->Subject = "Your request ";
$mail->Body = $message;
// final sending and check
if($mail->Send()) {
$_SESSION["feedback_positive"][] = FEEDBACK_CONTACT_MAIL_SENDING_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_CONTACT_MAIL_SENDING_ERROR . $mail- >ErrorInfo;
return false;
}
}
First up, you should really check the PHPMailer documentation first since there is an example that does exactly this. You can't have been looking too hard.
In your code, don't create a new PHPMailer instance every time around the loop - all the things that remain the same (isSmtp, Host, Port, etc) should be set once, before the loop. Inside the loop you should do these things:
Set the message body
Set the recipient
Send the message
Store any errors
Clear the recipient list (use clearAllRecipients())
You've also got return statements after your send check - these will exit your function completely, so it will never send more than one message. You should gather the errors as you go through your list and present (or return) them at the end.
I used a while loop just around the addAddress as suggested by #synchro above. Foreach iterator syntax wouldn't work as I'm using PHP 5.3 (as per comment in the link to PHPmailer above).
Then I took the return outside the while loop and everything worked just fine.
This is the code that worked:
(Any improvements on it gratefully accepted)
public function sendOrderEmail($customer_order_id)
{
$sql3 = " SELECT DISTINCT w.user_id AS supplier_id,
s.trading_name AS supplier_name,
s.contact_email AS supplier_email
FROM supplier_info AS s
JOIN wine AS w ON w.user_id = s.id
JOIN order_detail AS o ON o.wine_id = w.id
WHERE o.order_no_id = :customer_order_id ORDER BY supplier_id DESC;";
$query3 = $this->db->prepare($sql3);
$query3->execute(array(':customer_order_id' => intval($customer_order_id)));
$mail = new PHPMailer;
if (EMAIL_USE_SMTP) {
$mail->IsSMTP();
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
$mail->SMTPDebug = PHPMAILER_DEBUG_MODE;
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
$mail->SMTPKeepAlive = true;
if (defined('EMAIL_SMTP_ENCRYPTION')) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
} else {
$mail->IsMail();
}
$mail->isHTML(true);
$mail->From = "billyjlennon#gmail.com";
$mail->FromName = "Me";
while ($row3 = $query3->fetch(PDO::FETCH_ASSOC)) {
// Build email body
$message = "<p>hello</p>";
// fill mail with data
$mail->AddAddress($row3['supplier_email']);
$mail->Subject = "Your request to " . $row3['supplier_name'];
$mail->Body = $message;
// final sending and check
if ($mail->Send()) {
// $_SESSION["feedback_positive"][] = FEEDBACK_CONTACT_MAIL_SENDING_SUCCESSFUL;
//return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_CONTACT_MAIL_SENDING_ERROR . $mail->ErrorInfo;
// return false;
break;
}
$mail->ClearAddresses();
}
return true;
}