I am having problems getting php to redirect after processing an email message. I've tried all of the solutions mentioned on this page, as well as some involving javascript with no luck. Here are the relevant portions of my code:
function redirect($url) {
ob_start();
header('Location: '.$url);
ob_end_flush();
exit();
}
if ( isset($_REQUEST['sendemail']) ) {
header("Content-Type: text/plain");
header("X-Node: $hostname");
$from = $_REQUEST['from'];
$name = $_REQUEST['name'];
$toemail = "djsuson#gmail.com";
$subject = "Customer question";
$message = $_REQUEST['message'];
ob_start(); //start capturing output buffer because we want to change output to html
$mail = new PHPMailer;
$mail->SMTPDebug = 2;
$mail->IsSMTP();
if ( strpos($hostname, 'cpnl') === FALSE ) //if not cPanel
$mail->Host = 'relay-hosting.secureserver.net';
else
$mail->Host = 'localhost';
$mail->SMTPAuth = false;
$mail->From = $from;
$mail->FromName = $name;
$mail->AddAddress($toemail);
$mail->Subject = $subject;
$mail->Body = $message;
$mailresult = $mail->Send();
$mailconversation = nl2br(htmlspecialchars(ob_get_clean()));
if ( !$mailresult ) {
echo 'FAIL: ' . $mail->ErrorInfo . '<br />' . $mailconversation;
redirect('http://otterlywoods.com/failure.html');
} else {
echo $mailconversation;
redirect('http://otterlywoods.com/success.html');
}
Any help on this would be appreciated.
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.
I am trying to send email with multiple attachments using PHPMailer class. Multiple files are uploading successfully in directory but it's sending just one file in Email. And how to format my email body using bootstrap? Your suggestions will be highly appreciated. I am using PHPMailer 6.0.5
Here is my PHP Code:
<?php
$msg = '';
use PHPMailer\PHPMailer\PHPMailer;
include_once 'PHPMailer/PHPMailer.php';
include_once 'PHPMailer/Exception.php';
// include_once 'PHPMailer/SMTP.php';
if (isset($_POST['submit'])) {
$inputZip = $_POST['inputZip'];
$selectService = $_POST['selectService'];
$lawnMovingService = $_POST['lawnMovingService'];
$leafRemovalService = $_POST['leafRemovalService'];
$snowPlowingService = $_POST['snowPlowingService'];
$handymanService = $_POST['handymanService'];
$inputName = $_POST['inputName'];
$inputEmail = $_POST['inputEmail'];
$inputPhone = $_POST['inputPhone'];
$inputMessage = $_POST['inputMessage'];
if (isset($_FILES['images']['name']) && $_FILES['images']['name'] != '') {
$destination = "attachment/";
foreach ($_FILES["images"]["tmp_name"] as $key => $value) {
$tmp_name = $_FILES["images"]["tmp_name"][$key];
$name = $destination . basename($_FILES["images"]["name"][$key]);
move_uploaded_file($tmp_name, $name);
}
} else {
$name = '';
}
$mail = new PHPMailer;
//For SMTP
//$mail->Host = "smtp.gmail.com";
//$mail->isSMTP(); // This line may cause problem
//$mail->SMTPAuth = true;
//$mail->Username = "example#gmail.com";
//$mail->Password = "examplePassword";
//$mail->SMTPSecure = "ssl"; //OR TLS
//$mail->Port = 465; //TLS : 587
$mail->addAddress('milan.uptech#gmail.com');
$mail->setFrom($inputEmail);
$mail->Subject = 'Service Booking from Website';
$mail->isHTML(true);
$mail->Body = $inputMessage;
$mail->addAttachment($name);
if ($mail->send()) {
header('Location: index.php');
} else {
header('Location: contact.php');
}
// if(sendemail('milan.uptech#gmail.com', $email, $name, $body, $file)) {
// $msg = 'Email Sent!';
// sendemail($inputEmail, 'milan.uptech#gmail.com', $inputName, 'We have received your email');
// }
}
I moved the class creation up to be before the file file processing loop, and moved the attachment code in to the loop
<?php
$msg = '';
use PHPMailer\PHPMailer\PHPMailer;
include_once 'PHPMailer/PHPMailer.php';
include_once 'PHPMailer/Exception.php';
// include_once 'PHPMailer/SMTP.php';
if (isset($_POST['submit'])) {
$inputZip = $_POST['inputZip'];
$selectService = $_POST['selectService'];
$lawnMovingService = $_POST['lawnMovingService'];
$leafRemovalService = $_POST['leafRemovalService'];
$snowPlowingService = $_POST['snowPlowingService'];
$handymanService = $_POST['handymanService'];
$inputName = $_POST['inputName'];
$inputEmail = $_POST['inputEmail'];
$inputPhone = $_POST['inputPhone'];
$inputMessage = $_POST['inputMessage'];
$mail = new PHPMailer; //moved here
if (isset($_FILES['images']['name']) && $_FILES['images']['name'] != '') {
$destination = "attachment/";
foreach ($_FILES["images"]["tmp_name"] as $key => $value) {
$tmp_name = $_FILES["images"]["tmp_name"][$key];
$name = $destination . basename($_FILES["images"]["name"][$key]);
move_uploaded_file($tmp_name, $name);
$mail->addAttachment($name); //attache here
}
} else {
$name = '';
}
//For SMTP
//$mail->Host = "smtp.gmail.com";
//$mail->isSMTP(); // This line may cause problem
//$mail->SMTPAuth = true;
//$mail->Username = "example#gmail.com";
//$mail->Password = "examplePassword";
//$mail->SMTPSecure = "ssl"; //OR TLS
//$mail->Port = 465; //TLS : 587
$mail->addAddress('milan.uptech#gmail.com');
$mail->setFrom($inputEmail);
$mail->Subject = 'Service Booking from Website';
$mail->isHTML(true);
$mail->Body = $inputMessage;
if ($mail->send()) {
header('Location: index.php');
} else {
header('Location: contact.php');
}
// if(sendemail('milan.uptech#gmail.com', $email, $name, $body, $file)) {
// $msg = 'Email Sent!';
// sendemail($inputEmail, 'milan.uptech#gmail.com', $inputName, 'We have received your email');
// }
}
I'm trying to send an email to multiple recipients using phpmailer and getting the emails list from my table in the database, however, whenever I make a request only one recipient, the first one on the list gets the email. *I know this might be marked as duplicate but I couldn't find a similar example using mysql
<?php
if (isset($_POST['submit'])) {
if (empty($errors)) {
$thisType = mysql_prep($_POST["partner_type"]);
$content = $_POST["content"];
$header = $_POST["header"];
$query = "SELECT * FROM partners_list WHERE partner_type = '$thisType' ";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result)){
require_once("phpMailer/class.phpmailer.php");
require_once("phpMailer/class.smtp.php");
require_once("phpMailer/language/phpmailer.lang-uk.php");
$to_name = "Order";
$subject = $header;
$message = $content;
$message = wordwrap($message,70);
$from_name = "thisCompany";
$from = "noreply#thicCompany.com";
$mail = new PHPMailer();
$mail->AddAddress($row['email'], "Test Message"); // add each DB entry to list of recipients
$mail->FromName = $from_name;
$mail->From = $from;
$mail->Subject = $subject;
$mail->Body = $message;
$result = $mail->Send();
// Success
$_SESSION["message"] = "e-mail successfully sent.";
redirect_to("successpage.php");
}
}
} else {
}
?>
I have a HTML form that is being processed by a php page. I have had it working exactly as I need using mail() but am running into issues with the email part. Sending an email out is very inconsistent which is not acceptable. I understand that mail() only takes care of a small part of the process and the mail servers take care of the heavy lifting.
I am trying out PHPMailer as an alternative. I have it up and running and am able to get mail to go out but some of the functionality is not there.
In my form you can add multiple 'projects' to a single submission. The php is supposed to loop over those projects and create a section for each in the email. Again, this is working with mail() but doesn't always send.
The code I am trying to implement is below. It will send an email but will not loop over the form fields if there are more than one. It will only see the last one entered.
<?php
require 'PHPMailerAutoload.php';
date_default_timezone_set('America/New_York');
$today = date("F j - Y - g:i a");
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mail#example.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'mail#example.com';
$mail->FromName = 'From name';
$mail->addAddress('mail#example.com', 'personName'); // Add a recipient
//$mail->addAddress('mail#anotherexample.com'); // Name is optional
$mail->addReplyTo('mail#example.com', 'replyTO');
//$mail->addCC('cc#example.com');
//$mail->addBCC('bcc#example.com');
$mail->WordWrap = 500; // 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
//VARIABLES FROM FORM FIELDS
$contractor = $_POST['ct'];
$noactive = $_POST['noconactivity'];
$hours = $_POST['hours'];
$project = $_POST['prjx'];
$city = $_POST['cx'];
$street = $_POST['street'];
$from = $_POST['from'];
$to = $_POST['to'];
$crewxtown = $_POST['cxtown'];
$construction = $_POST['construction'];
$mpt = $_POST['mpt'];
$direction = $_POST['direction'];
$police = $_POST['police'];
$optcomments = $_POST['optcomments'];
$submissionemail = $_POST['submissionemail'];
$mail_cm = $_POST['cm'];
$mail_pm = $_POST['pm'];
$intersection = $_POST['intersection'];
$parking = $_POST['parking'];
$count = count($street)-1;
$data = array();
//REPETITIVE VARIABLES
for( $i = 0; $i <= $count; $i++ )
{
$hours0 = $hours[$i];
$street0 = $street[$i];
$from0 = $from[$i];
$to0 = $to[$i];
$crewxtown0 = $crewxtown[$i];
$construction0 = $construction[$i];
$mpt0 = $mpt[$i];
$direction0 = $direction[$i];
$police0 = $police[$i];
$optcomments0 = $optcomments[$i];
$parking0 = $parking[$i];
$intersection0 = $intersection[$i];
$data[] = "$today, $noactive, $contractor, $hours0, $project, $city, $street0, $from0, $to0, $intersection0, $construction0, $mpt0, $crewxtown0, $direction0, $police0, $parking0, $optcomments0, $submissionemail, $mail_cm, $mail_pm\n";
$mail->Subject = $project;
$mail->Body = 'Message content header stuff.<br><br><br><b>Street: </b> ' . $street0;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
}
// WRITING DATA TO CSV TABLE
if(!empty($data)) {
$data = implode('', $data);
$fh = fopen("dailyupdatedata.csv", "a");
fwrite($fh, $data);
fclose($fh);
}
//SUCCESS & FAILURE MESSAGE ON PHP PAGE
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
Here is the mail() code that works but does not consistently send.
<?php
date_default_timezone_set('America/New_York');
$contractor = $_POST['ct'];
$noactive = $_POST['noconactivity'];
$hours = $_POST['hours'];
$project = $_POST['prjx'];
$city = $_POST['cx'];
$street = $_POST['street'];
$from = $_POST['from'];
$to = $_POST['to'];
$crewxtown = $_POST['cxtown'];
$construction = $_POST['construction'];
$mpt = $_POST['mpt'];
$direction = $_POST['direction'];
$police = $_POST['police'];
$optcomments = $_POST['optcomments'];
$submissionemail = $_POST['submissionemail'];
$mail_cm = $_POST['cm'];
$mail_pm = $_POST['pm'];
$intersection = $_POST['intersection'];
$parking = $_POST['parking'];
$count = count($street)-1;
$today = date("F j - Y - g:i a");//
$message = '<html><body>';
$message .= "Please see the info blah blah<br><strong>Date:</strong> $today<br><strong>Submission by:</strong> $submissionemail<br><br>"; // Beginning message content
$data = array();
for( $i = 0; $i <= $count; $i++ )
{
$hours0 = $hours[$i];
$street0 = $street[$i];
$from0 = $from[$i];
$to0 = $to[$i];
$crewxtown0 = $crewxtown[$i];
$construction0 = $construction[$i];
$mpt0 = $mpt[$i];
$direction0 = $direction[$i];
$police0 = $police[$i];
$optcomments0 = $optcomments[$i];
$parking0 = $parking[$i];
$intersection0 = $intersection[$i];
$data[] = "$today, $noactive, $contractor, $hours0, $project, $city, $street0, $from0, $to0, $intersection0, $construction0, $mpt0, $crewxtown0, $direction0, $police0, $parking0, $optcomments0, $submissionemail, $mail_cm, $mail_pm\n";
$message .= "<strong>Project:</strong> $project<br><strong>Active / Not Active:</strong> $noactive<br><strong>Contractor:</strong> $contractor<br><strong>Town:</strong> $city<br><strong>Hours:</strong> $hours0<br><strong>Street:</strong> $street0<br><strong>From:</strong> $from0<br><strong>To:</strong> $to0<br><strong>Intersection:</strong> $intersection0<br><strong>Construction Activity:</strong> $construction0<br><strong>MPT:</strong> $mpt0<br><strong>Crew Town:</strong> $crewxtown0<br><strong>Closure Direction:</strong> $direction0<br><strong>Police & Flaggers:</strong> $police0<br><strong>Parking Restrictions:</strong> $parking0<br><strong>Optional Comments:</strong> $optcomments0<br><br> -- <br><br>"; //Data for message
}
$message .= '</body></html>';
if(!empty($data)) {
$data = implode('', $data);
$fromemail = "email#email.com"; // email#email.com
$subject = $project;
//$headers = "From:" . $fromemail;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: "."Team Traffic "." <email#email.com>" . "\r\n";
mail($submissionemail,$subject,$message,$headers); // Submission Email
mail($mail_cm,$subject,$message,$headers); // C Manager Email
mail($mail_pm,$subject,$message,$headers); // P Manager Email
mail("email#email",$subject,$message,$headers);
//mail($trafficemail,$subject,$message,$headers); // Traffic
$fh = fopen("dailyupdatedata.csv", "a");
fwrite($fh, $data);
fclose($fh);
}
?>
Am I missing a step here? Does PHPMailer not work with looping over variables?
Thank you,
Eric
$mail->Body = 'Message content header stuff.<br><br><br><b>Street: </b> ' . $street0;
You are doing that in a loop, that means your code is overwriting the email body on every iteration and only the last one will stay. And then you exit the loop and send the email.
You should be appending those values to the body instead of overwriting the value.
$mail->Body.="New content for new project";
^
I think $mail->Subject = $project; should be out of the loop.
As for body I think you forgot adding a dot(.=) to accumulate the message.
$mail->Body .= 'Message content header stuff.<br><br><br><b>Street: </b> ' . $street0;