warning in base64_encode of in phpmailer class - php

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.

Related

How to send 2 emails with only one PHP contact form

I'm learning PHP and coding and am looking for a way to send 2 email confirmation with this PHP code. I tried to duplicate my mail function but didn't work. I'm not sure I have to duplicate the SMTP part too or not.
What can I try next?
<?php
use PHPMailer\PHPMailer\PHPMailer;
if ( isset ($_POST['name']) and isset ($_POST['email']) and isset ($_POST['message']) ){
$url = $_POST['url'];
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$rappel = $_POST['period'];
$message = $_POST['message'];
$address = $_POST['address'];
$ville = $_POST['city'];
$net = $_POST['net'];
$tv = $_POST['tv'];
$tel = $_POST['tel'];
$file_attach = $_FILES['file']['tmp_name'];
$file_attach_name = $_FILES['image']['name'];
$msg = '';
if (array_key_exists('email', $_POST)) {
date_default_timezone_set('Etc/UTC');
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "xxx#xxx.com";
$mail->Password = "";
$mail->setFrom('xxx#xxx.com');
$mail->addReplyTo('$email', '$name');
$cnt=count($_FILES['file']['name']);
if($cnt > 0){
for($i=0;$i<$cnt;$i++){
$mail->AddAttachment($_FILES['file']['tmp_name'][$i], $_FILES['file']['name'][$i],'base64',$_FILES['file']['type'][$i]);
}
}
if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
//Set the subject line
$mail->Subject = 'Message de votre site ' . $client . ' - ' . $name;
//Keep it simple - don't use HTML
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
//Build a simple message body
$mail->Body = file_get_contents('rd-mailform.tpl');
$mail->Body = str_replace(
["<!-- #{StartName} -->", "<!-- #{Name} -->"],
["Nom:", $_POST['name']],
$mail->Body);
$mail->Body = str_replace(
["<!-- #{StartPhone} -->", "<!-- #{Phone} -->"],
["Téléphone:", $_POST['phone']],
$mail->Body);
$mail->Body = str_replace(
["<!-- #{StartEmail} -->", "<!-- #{Email} -->"],
["Email:", $_POST['email']],
$mail->Body);
$mail->Body = str_replace(
["<!-- #{StartRappel} -->", "<!-- #{Rappel} -->"],
["Période de rappel:", $_POST['period']],
$mail->Body);
$mail->Body = str_replace(
["<!-- #{MessageStart} -->", "<!-- #{Message} -->"],
["Message:", $_POST['message']],
$mail->Body);
$mail->Body = $mail->Body."Adresse IP de l'expéditeur: $ssIPAddress / Localisation <a href='http://ipinfodb.com/ip_locator.php?ip=$ssIPAddress'>ici</a>, <a href='http://www.ip-tracker.org/ip-to-location.php?ip=$ssIPAddress'>ici</a> et <a href='http://whatismyipaddress.com/ip/$ssIPAddress'>ici</a></p>";
//Send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
print "<meta http-equiv=\"refresh\" content=\"0;URL=success.php\">";
}
}
?>

htmlentities ignores <br> when using PHPmailer

Some times ago I made a contact form to send email.
I had this:
If ($validity !='Good#Ripsi'){
$to = "contact-us#xx-xxxx.com";
$subject = "xx xxxx new Subscriber";
$email_address = htmlentities($_GET['email_address']);
$headers = "xxxxxxxxxx" . "\r\n" .
mail($to,$subject,$email_address,$headers);
header("Location: index.php");
}
And that worked fine. After I read that although I don't plan to send thousands of Newletters it would be better to use PHPmailer else it could be seen as spam and be blocked. I don't understand much about those mailing things. So I read a tutorial and it works just fine but for one thing: htmlentities doesn't do the job anymore and all <br> are ignored at reception.
I checked that : $mail->IsHTML(true);
Help would be greatly appreciated.
Here is the code using PHPMailer:
<?php
require "phpmailer/PHPMailer/PHPMailerAutoload.php";
define("DB_HOST","localhost");
define("DB_USERNAME","xxxx_xxxx");
define("DB_PASSWORD","xxxx");
define("DB_NAME","xxxxxx");
$conn = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die (mysqli-error());
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function smtpmailer($to, $from, $from_name, $subject, $body)
{
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'mail.xxxxx.com';
$mail->Port = 465;
$mail->Username = 'newsletter#xxxxx.com';
$mail->Password = 'xxxxxxx';
$mail->IsHTML(true);
$mail->From="newsletter#xxxx.com";
$mail->FromName=$from_name;
$mail->Sender=$from;
$mail->AddReplyTo($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send())
{
$error ="Error Ocured...";
return $error;
}
else
{
$error = "Please wait!! Your email is being sent... ";
return $error;
}
}
$from = 'newsletter#ts-ripsi.com';
$name = 'xxxxxxx T & S';
$subj = 'Newsletter from xxx and xxxx';
$msg = htmlentities($_GET['message']);
$sqli = "SELECT ID, Email FROM mailing_addresses";
$record = mysqli_query($conn, $sqli);
while ($row = mysqli_fetch_array($record)) {
$to = $row['Email'];
$error=smtpmailer($to,$from, $name ,$subj, $msg);
}
header("Location: index.php");
?>
I hadn't understood the use of IsHTML. In this case it had to be set to false.

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

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);

Attachments working intermittently

I am having issues with my phpMailer script. I can email from the script, I can even send attachments from the script. However, it only works SOMETIMES and not at other times. I tried changing servers and I have the same issues so I am assuming that it is a coding issue.
when It does not work, the emails still go thorough but it is stripped from any attachments.
The attachments are definitely making it onto the server in the same location and then this script is sent an array of attachments which it then adds onto the message.
In one instance the same code and same files will send and not send! Very confusing! Usually some will send for awhile and then some will not for awhile.
Here is the code:
<?php
include('connection.php');
require_once('PHPMailer/PHPMailerAutoload.php');
class Mailer extends PHPMailer {
public function copyToFolder($folderPath) {
$message = $this->MIMEHeader . $this->MIMEBody;
$path = "INBOX" . (isset($folderPath) && !is_null($folderPath) ? ".".$folderPath : ""); // Location to save the email
$imapStream = imap_open("{mail.server.com:143/novalidate-cert}" . $path , $this->Username, $this->Password) or die(mysql_error());
imap_append($imapStream, "{mail.server.com:143/novalidate-cert}" . $path, $message)or die(mysql_error());
}
imap_close($imapStream);
}
}
$from = $_POST['from'];
$username = $from;
$grabPassword = mysql_query("SELECT * FROM `email_pw_db` WHERE `emailaddress` = '$from'");
$fetchPassword = mysql_fetch_assoc($grabPassword);
$password = $fetchPassword['password'];
$company = $_POST['to'];
$toemail = $_POST['toemail'];
$from = $username;
$namefrom = $_POST['from'];
$subject = $_POST['subject'];
$cc = trim($_POST['cc']);
$bcc = trim($_POST['bcc']);
$message = $_POST['body'];;
$attachments = $_POST['attachments'];
$mail = new Mailer();
$body = $message;
/*Create a new email*/
$mail = new Mailer();
$mail->isSMTP();
$mail->Host = 'mail.server.com';
$mail->Username = $username;
$mail->Password = $password;
$mail->From = $from;
$mail->AddReplyTo($from,$namefrom);
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->SetFrom($from, $namefrom);
$mail->AddReplyTo($from,$namefrom);
$address = $toemail;
$mail->AddAddress($address, $company);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
if($cc!=''){
$mail->addCC($cc);
}
//CC EMAILS//
$breakOutCC = explode(',', $cc);
$countBreakOut = count($breakOutCC);
$i = 0;
while($i <$countBreakOut)
{
$mail->addCC($breakOutCC[$i]);
$i++;
}
$breakOutBCC = explode(',', $bcc);
$countBreakOutBCC = count($breakOutBCC);
$i = 0;
while($i <$countBreakOutBCC)
{
$mail->addBCC($breakOutBCC[$i]);
$i++;
}
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
$mail->AddAttachment("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
$errorMessage = $mail->ErrorInfo;
header( 'Location: email-software.php?dialog=Whoops Something Happened- '.$errorMessage ) ;
} else {
//$mail->copyToFolder(); //save email
$mail->copyToFolder("Sent"); // Will save into Sent folder
$attachments = $_POST['attachments'];
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
unlink("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
header( 'Location: email-software.php?dialog=email sent' ) ;
}
?>

PHPMailer failing

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.

Categories