When i am trying to send an excel sheet as attachment in php, it shows that cannot access the file. But if i am commenting the attachment part, the mail will send perfectly. When i am trying to download the sheet it works perfectly.
Will anyone guide me how can i fix this problem?
Thank you
$select="select * from tablename";
$export = mysql_query($select);
$fields = mysql_num_fields($export);
$csv_output = '';
$data='';
for ($i = 0; $i < $fields; $i++) {
$csv_output .= mysql_field_name($export, $i) . "\t";
}
while ($row = mysql_fetch_row($export)) {
$line = '';
foreach ($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "NULL\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line) . "\n";
}
$data = str_replace("\r", "", $data);
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username ='xxxx#gmail.com';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('xxxxx#gmail.com', 'name');
$mail->addAddress('xxxxx#gmail.com', 'name');
$mail->addAttachment($csv_output . "\n" . $data);
$mail->isHTML(true);
$mail->Subject = 'Report';
$mail->Body = '<b>Please find the attachment of the Report</b>';
$mail->AltBody = 'Please find the attachement of the Report';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
addAttachment expects a path to a file, not raw attachment content. Easiest fix would be to store your attachment content to a temporary file and then give the path to that.
So instead of:
$mail->addAttachment($csv_output . "\n" . $data);
You could do something like:
$report_filename = date('Y-m-d-his-').'-report.txt';
file_put_contents($report_filename, $csv_output . "\n" . $data);
$mail->addAttachment($report_filename);
//....
$mail->send();
unlink($report_filename);
Related
I am using following code to take backup of my mysql database.
With this code, a file is created and get saved in same folder where this script is kept. It is working perfectly.
I am trying to email this file using phpmailer. But I am stucked as no file is getting attached to receiving email. (email is delivered without attached file...)
Basic code is taken from https://write.corbpie.com/php-pdo-mysql-backup-script-with-compression-option/
Help is appreciated... and thank you in advanced...
Backup creating code part is as follows :
<?php
include_once("../../include/mysqli_constants.php");
require("../../PHPMailer/class.phpmailer.php");
$db_server = constant('HST');
$db_name = constant('DBN');
$db_user = constant('USR');
$db_pass = constant('PWD');
$site_url = constant('FILEROOT');
$from_email = constant('FROMEMAIL');
$from_name = constant('FROMNAME');
$mail_to1 = 'mypersonal#gmail.com';
$mail_to1_name = 'Dr Manish Joshi';
$mail_to2 = '';
$mail_to2_name = '';
$save_dir = './';
$file_name_prefix = 'my_website_';
$date = strtolower(date('d_F_Y_H_i_s_A'));
/* Do NOT EDIT BELOW */
$backup_config = array(
'DB_HOST' => $db_server,////Database hostname
'DB_NAME' => $db_name,//Database name to backup
'DB_USERNAME' => $db_user,//Database account username
'DB_PASSWORD' => $db_pass,//Database account password
'INCLUDE_DROP_TABLE' => false,//Include DROP TABLE IF EXISTS
'SAVE_DIR' => '',//Folder to save file in
'SAVE_AS' => $file_name_prefix,//Prepend filename
'APPEND_DATE_FORMAT' => 'Y_m_d_H_i_s',//Append date to file name
'TIMEZONE' => 'Asia/Kolkata',//Timezone for date format
'COMPRESS' => true,//Compress into gz otherwise keep as .sql
);
echo backupDB($backup_config);
Email sending part is as follows :
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->Host = constant('EMAILHOST');
$mail->AddAddress(''.$mail_to1.'', ''.$mail_to1_name.'');
$mail->IsSMTP();
$mail->SMTPAuth = constant('SMTPAuth');
$mail->SMTPSecure = 'tls';
$mail->Mailer = "smtp";
$mail->SMTPDebug = constant('SMTPDEBUG');
$mail->Username = constant('SMTPUSERNAME');
$mail->Password = constant('SMTPPASSWORD');
$mail->Port = 587;
$mail->From = constant('FROMEMAIL');
$mail->FromName = constant('FROMNAME');
$mail->WordWrap = 50;
$mail->Subject = '['.$from_name.'] Cron Backup MySQL On - ' . $date;
$mail->Body = $save_string.' File is attached via cron';
$mail->AddAttachment($save_string);
if (!$mail->AddAttachment($save_string)) {
echo 'Erreur : ' . $mail->ErrorInfo . "\n";
$mail->Body .= "\n" . 'Erreur : ' . $mail->ErrorInfo;
}
if (!$mail->Send()){
echo 'Message could not be sent. <p>';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
Function to create database backup is as follows and it is working OK and creating db backup and saving file in folder.
/* FUNCTION Starts */
function backupDB(array $config): string {
$db = new PDO("mysql:host={$config['DB_HOST']};dbname={$config['DB_NAME']}; charset=utf8", $config['DB_USERNAME'], $config['DB_PASSWORD']);
$db->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
date_default_timezone_set($config['TIMEZONE']);
$do_compress = $config['COMPRESS'];
if ($do_compress) {
$save_string = $config['SAVE_AS'] . $config['SAVE_DIR'] . date($config['APPEND_DATE_FORMAT']) . '.sql.gz';
$zp = gzopen($save_string, "a9");
} else {
$save_string = $config['SAVE_AS'] . $config['SAVE_DIR'] . date($config['APPEND_DATE_FORMAT']) . '.sql';
$handle = fopen($save_string, 'a+');
}
//array of all database field types which just take numbers
$numtypes = array('tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'double', 'decimal', 'real');
$return = "";
$return .= "CREATE DATABASE `{$config['DB_NAME']}`;\n";
$return .= "USE `{$config['DB_NAME']}`;\n";
//get all tables
$pstm1 = $db->query('SHOW TABLES');
while ($row = $pstm1->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
//cycle through the table(s)
foreach ($tables as $table) {
$result = $db->query("SELECT * FROM $table");
$num_fields = $result->columnCount();
$num_rows = $result->rowCount();
if ($config['INCLUDE_DROP_TABLE']) {
$return .= 'DROP TABLE IF EXISTS `' . $table . '`;';
}
//table structure
$pstm2 = $db->query("SHOW CREATE TABLE $table");
$row2 = $pstm2->fetch(PDO::FETCH_NUM);
$ifnotexists = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $row2[1]);
$return .= "\n\n" . $ifnotexists . ";\n\n";
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
//insert values
if ($num_rows) {
$return = 'INSERT INTO `' . $table . '` (';
$pstm3 = $db->query("SHOW COLUMNS FROM $table");
$count = 0;
$type = array();
while ($rows = $pstm3->fetch(PDO::FETCH_NUM)) {
if (stripos($rows[1], '(')) {
$type[$table][] = stristr($rows[1], '(', true);
} else {
$type[$table][] = $rows[1];
}
$return .= "`" . $rows[0] . "`";
$count++;
if ($count < ($pstm3->rowCount())) {
$return .= ", ";
}
}
$return .= ")" . ' VALUES';
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$counter = 0;
while ($row = $result->fetch(PDO::FETCH_NUM)) {
$return = "\n\t(";
for ($j = 0; $j < $num_fields; $j++) {
if (isset($row[$j])) {
//if number, take away "". else leave as string
if ((in_array($type[$table][$j], $numtypes)) && (!empty($row[$j]))) {
$return .= $row[$j];
} else {
$return .= $db->quote($row[$j]);
}
} else {
$return .= 'NULL';
}
if ($j < ($num_fields - 1)) {
$return .= ',';
}
}
$counter++;
if ($counter < ($result->rowCount())) {
$return .= "),";
} else {
$return .= ");";
}
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$return = "\n\n-- ------------------------------------------------ \n\n";
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$error1 = $pstm2->errorInfo();
$error2 = $pstm3->errorInfo();
$error3 = $result->errorInfo();
echo $error1[2];
echo $error2[2];
echo $error3[2];
if ($do_compress) {
gzclose($zp);
} else {
fclose($handle);
}
return "{$config['DB_NAME']} saved as $save_string";
}
?>
I have edited this code and now it is working...
Edited code kept on github...
https://github.com/vaidyamanishjoshi/db-backup-with-pdo-and-email-it
I have a table in the db that queues and stores all the mails that are sent through a script that inserts data into this table.
Another script in php manages the sending, given the high number of emails, to avoid spamming it sends them in groups of 50.
it repeats the loop until all the tuples have been sent.
(there is a column for each tuple with queued or sent set)
The problem is the following:
Given, precisely, the high number of submissions, at a certain point the script crashes (chrome) with the error "ERR_TOO_MANY_REDIRECTS".
How can i resolve?
<?php
require_once '../dbh.inc.php';
include_once '../functions.php';
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
require '../PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail-> isSMTP();
$mail->Host = 'smtps.*****.it';
$mail->SMTPDebug = 0;
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = 'ssl';
$mail->Username = 'intranet#*****.it';
$mail->Password = '*****';
$mail->Priority = '1';
$mail->setFrom('intranet#*****.it', '*****');
$process_count = 50;
$sql = "SELECT * FROM `email_queue` WHERE `status` = 'queued' AND `do_not_send_before` < '" .strtotime("now") ."'
ORDER BY `submission_date`, `priority` ASC LIMIT $process_count ";
$result = mysqli_query($conn, $sql);
foreach ($result as $row) {
$mail->addAddress($row['recipient']);
$mail->addReplyTo($row['reply_to']);
$mail->IsHTML(true);
$mail->CharSet = "UTF-8";
$mail->Subject = $row['subject'];
$mail->msgHTML($row['message']);
$mail->AltBody = "";
$file1 = $row['file1'];
$file2 = $row['file2'];
$file3 = $row['file3'];
$file4 = $row['file4'];
$file5 = $row['file5'];
$filepath = '/web/htdocs/www.*****.it/home/it/intranet/uploads/mails/';
if (!empty($file1)) {
$file1 = $filepath.$file1;
$mail->AddAttachment($file1);
}
if (!empty($file2)) {
$file2 = $filepath.$file2;
$mail->AddAttachment($file2);
}
if (!empty($file3)) {
$file3 = $filepath.$file3;
$mail->AddAttachment($file3);
}
if (!empty($file4)) {
$file4 = $filepath.$file4;
$mail->AddAttachment($file4);
}
if (!empty($file5)) {
$file5 = $filepath.$file5;
$mail->AddAttachment($file5);
}
if (!$mail->send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["recipient"]) . ') ' . $mail->ErrorInfo . '<br />';
break; //Abandon sending
} else {
$now = strtotime("now");
//echo "Messaggio inviato a :" . ' (' . str_replace("#", "#", $row['recipient']) . ')<br />';
//Mark it as sent in the DB
$sql1 = "UPDATE `email_queue` SET `status` = 'sent', `sent_date` = '$now' WHERE `id` = '" . $row['id'] . "'";
$result = mysqli_query($conn, $sql1);
if ($result) {
echo "Mail Inviata correttamente a: (" . str_replace("#", "#", $row["recipient"]) . ') <br />';
} else {
echo "error $sql1 </br>";
}
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
$mail->clearAttachments();
}
$sql2 = "SELECT COUNT(*) AS count FROM `email_queue` WHERE `status` = 'queued';";
$result2 = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_assoc($result2);
$count = $row2['count'];
echo "$count";
if ($count > 0) {
header('Location: '.$_SERVER['PHP_SELF']);
} else {
header('Location:' . $USER_LOCATION . "index.php?emails=success");
}
?>
At the end of script, you have else-if condition which always results in a redirect. If the count of rows is bigger than 0, you redirect it to the same script, without end. It results in a never-ending loop of redirects.
Just do not redirect in this case, or redirect to another script that won't redirect to another (or the same) script again.
pseudo code:
if ($count > 0) {
// do something here instead of redirect
} else {
header('Location:' . $USER_LOCATION . "index.php?emails=success");
}
header('Location: '.$_SERVER['PHP_SELF']); always redirects to same URL and there server sees infinite redirect, that's why TOO_MANY_REDIRECTS.
Do not use re-directs here. Use loop.
do {
$count = $this->getCount();
if ($count > 0) {
$this->processEmails();
}
} while ($count > 0);
Note that this process may be executed longer than 30s and it would time out your ordinary browser request. Use it as CLI command
Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"
I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.
the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.
I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.
<?php
include 'db.php';
function check_emailaddress($email) {
// First, we check that there is one # symbol, and that the lengths are right
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $email))
{
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++)
{
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
{
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) // Check if domain is IP. If not, it should be valid domain name
{
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2)
{
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++)
{
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
{
return false;
}
}
}
return true;
}
$extraParam = "";
if (isset($_GET["ex"]) ) {
$extraParam = $_GET["ex"]."---";
}
//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail; //"From: info#visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6#gmail.com";
$email_to = "" ;//"respite#safeguards-training.net";
$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;
if ($usetemplate == 0) exit; // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info#visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
// $email_address = "lyan3000#gmail.com";
// if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
/*
echo $email_from . "<br>";
echo $email_address . "<br>";
echo $email_subject . "<br>";
echo $email_message;
echo "<hr>";
*/
if (mail($email_address, $email_subject, $email_message, $email_from))
{
//echo "Reminder email sent to: " . $no['firstname'] . "<br>";
echo "Yes. <br>";
}else{
//echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "<br>";
echo "No. <br>";
}
}
$file_name = "record_for_cron_expire_email.txt";
$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');
$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);
//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;
$variable = array(
'{$learnerCourse}' => $learnercourse,
'{$date}' => $date
);
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);
//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
SET a04Status = 0
WHERE a04ExpirationDate <= '$expiredRightNow'
AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.<br>$strSQL_setExpire");
?>
mysqli_result::fetch_all() requires MySQL Native Driver (mysqlnd).
chances are you might be missing it.
have a look at this posts, that might help you.
mysqli fetch_all() not a valid function?
below is the minimal code I can think of:
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
if (mail($email_address, $email_subject, $email_message, $email_from))
{
echo "Yes. <br>";
}else{
echo "No. <br>";
}
}
I have problem sending multiple email cc separated by coma symbol using PHPMailer . . i'm using PHP 7.
I have these data in my mysql database contains multiple email address in single user account separated by coma (,) .
I already follow the answer from this question here, but its not working. email can only be sent to john#mail.com . billy#mail.com did not receive any mail.
I tried to echo var_dump(maildbs);
output shown without coma . .
john#mail.combilly#mail.com
Here's my PHP code . .
sendmail.php
<?php
$connect = mysqli_connect("", "", "", "");
global $connect;
if(isset($_POST['Submit'])){
$staffname = $_POST['staffname'];
$sql = "SELECT * FROM table WHERE staff_name ='$staffname'";
$get = mysqli_query($connect,$sql);
if($get && mysqli_num_rows($get) > 0 )
{
while($row = mysqli_fetch_assoc($get))
{
$maildbs = explode(',',$row["email_address"]);
foreach($maildbs as $maildb){
date_default_timezone_set('Etc/UTC');
require_once '../PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "host";
$mail->Port = 25;
$mail->SMTPAuth = false;
$mail->setFrom('sender#mail.com', 'Sender');
$mail->addAddress('mail#mail.com','receipent');
$mail->addCC($maildb);
$mail->Subject = 'PHPMailer SMTP without auth test';
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
$mail->AltBody = 'This is a plain-text message body';
$mail->Body = 'body content';
$mail->addAttachment('images/phpmailer_mini.png');
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
}
mysqli_free_result($get);
}
}
?>
<!DOCTYPE html>
<html><title>Test Email</title></head>
<body>
<table>
<form action="sendmail.php" method="POST">
<tr>
<td>Staff Name :</td>
<td><input type="text" name="staffname" value="" ></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="send email"></td>
</tr>
</form>
</table>
</body>
</html>
Appreciate if someone can help.
use explode php function
$email = explode(',', $toEmail);
for ($i = 0; $i < count($email); $i++) {
$mail->addAddress($email[$i], 'recipient ');
}
if ($ccEmail != null) {
$emailCC = explode(',', $ccEmail);
for ($i = 0; $i < count($emailCC); $i++) {
$mail->addCC($emailCC[$i]);
}
}
if ($ccBCC != null) {
$emailBCC = explode(',', $ccBCC);
for ($i = 0; $i < count($emailBCC); $i++) {
$mail->addBCC($emailBCC[$i]);
}
}
i'm trying to loop a variable whose data populates from another loop of array's
HERE is the loop
for ($i=0; $i < $cid; $i++){
$message .= '<tr>
<td>'.$pcode.'</td>
<td>'.$pname.'</td>
<td>'.$pprice.'</td>
<td>'.$pqty.'</td>
</tr>';
}
And the variables in <td></td> are generated from this loop
foreach($_POST['item_cid'] as $key => $value) {
$cid = mysqli_real_escape_string($connection,$value);
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
}
I don't know how to make this loop work, I got no errors on submit,
am i looping it correctly?
The Updated Code:
<?php
session_start();
require('admin/connect.php');
require('includes/phpmailer/PHPMailerAutoload.php');
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$resultArr = array();
$i = 0;
foreach($_POST['item_cid'] as $key => $value) {
//Data for Orders Table
$cid = intval(mysqli_real_escape_string($connection,$value));
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
//SOLUTION FROM SANJAY
$resultArr[$i] = array('cid' => $cid, 'pcode' => $pcode, 'pname' => $pname, 'pprice' => $pprice, 'pqty' => $pqty);
$i++;
//Data for Customers Table
$cname = mysqli_real_escape_string($connection,$_POST['item_cname'][$key]);
$cemail = mysqli_real_escape_string($connection,$_POST['item_cemail'][$key]);
$cphone = mysqli_real_escape_string($connection,$_POST['item_cphone'][$key]);
$caddress = mysqli_real_escape_string($connection,$_POST['item_caddress'][$key]);
$ctotal = mysqli_real_escape_string($connection,$_POST['item_ctotal'][$key]);
//$sql = "INSERT INTO orders (cid, ordprod_code, ordprod_name, ordprod_price, ordprod_qty) VALUES ('$value', '$pcode', '$pname', '$pprice', '$pqty')";
//$sql2 = "INSERT INTO customers (cid, cname, cemail, cphone, caddress, ctotal) VALUES ('$value','$cname','$cemail','$cphone','$caddress','$ctotal')";
if ($connection->query($sql) === TRUE) {
echo "Orders record created successfully \n";
}
// } else {
// echo "Error: " . $sql . "<br>" . $connection->error;
// }
if ($connection->query($sql2) === TRUE) {
echo "Customers record created successfully \n";
}
// } else {
// echo "Error: " . $sql2 . "<br>" . $connection->error;
} // close the loop
print_r($resultArr);
//********************************
// START EMAIL FUNCTION
//********************************
$message = '<html><body>';
$message .= '<img src="http://cdn.example.com/static/images/emailhead.jpg" alt="MY Site" />';
$message .= '<h3>Customer Information:</h3>';
$message .= '<table rules="all" border="1" style="border-color: #ccc;" cellpadding="10">';
$message .= '<tr><td><strong>CustomerID</strong></td><td>'. $cid .'</td></tr>';
$message .= '<tr><td><strong>Name:</strong></td><td>'. $cname .'</td></tr>';
$message .= '<tr><td><strong>Email:</strong></td><td>'. $cemail .'</td></tr>';
$message .= '<tr><td><strong>Phone:</strong></td><td>'. $cphone .'</td></tr>';
$message .= '<tr><td><strong>Address:</strong></td><td>'. $caddress .'</td></tr>';
$message .= '</table>';
$message .= '<br />';
$message .= '<h3>Order Details:</h3>';
$message .= '<table rules="all" border="1" style="border-color: #ccc;" cellpadding="10">';
$message .= '<tr style="background:#eee;">
<td><strong>Product Code</strong></td>
<td><strong>Product Name</strong></td>
<td><strong>Product Price</strong></td>
<td><strong>Product Qty</strong></td>
</tr>';
// SOLUTION FROM SANJAY
$i = 0;
for ($i=0; $i < ((isset($resultArr[$i]['cid']) && count($resultArr[$i]['cid']) > 0 ) ?$resultArr[$i]['cid'] : 0); $i++)
{
$message .= '<tr>
<td>'.$resultArr[$i]['pcode'].'</td>
<td>'.$resultArr[$i]['pname'].'</td>
<td>'.$resultArr[$i]['pprice'].'</td>
<td>'.$resultArr[$i]['pqty'].'</td>
</tr>';
}
$message .= '<tr style="background:#eee;">
<td colspan="2">Total Amount</td>
<td>'.$ctotal.'</td>
<td></td>
</tr>';
$message .= '</table>';
$message .= '</body></html>';
$pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i";
if (preg_match($pattern, $cemail)) {
$cleanedFrom = $cemail;
} else {
return "The email address you entered was invalid. Please try again!";
}
//***************************************
// SEND MAIL USING GMAIL SMTP SERVER
//***************************************
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->Port = 587; //Set the SMTP port number - 587 for authenticated TLS
$mail->setFrom(''.$cemail.'', ''.$cname.''); //Set who the message is to be sent from
$mail->addReplyTo(''.$cemail.'', ''.$cname.''); //Set an alternative reply-to address
$mail->addAddress('owner#example.com', 'YAQOOB'); // Add a recipient
$mail->addAddress('owner#example.com'); // Name is optional
$mail->addCC('');
$mail->addBCC('');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->addAttachment('/user/file.doc'); // Add attachments
$mail->addAttachment('/images/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New order arrived from CustomerID #'.$cid.'';
$mail->Body = ''.$message.'';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
} // Data Inserted & Emailed Close IF Statement
session_destroy();
?>
Try this:
$message = "";
$resultArr = array();
$i = 0;
foreach($_POST['item_cid'] as $key => $value)
{
$cid = mysqli_real_escape_string($connection,$value);
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
$resultArr[$i] = array('cid' => $cid, 'pcode' => $pcode, 'pname' => $pname, 'pprice' => $pprice, 'pqty' => $pqty);
$i++;
}
$i = 0;
for ($i=0; $i < (isset($resultArr[$i]['cid']) && $resultArr[$i]['cid'] ?$resultArr[$i]['cid'] : 0); $i++)
{
$message .= '<tr>
<td>'.$resultArr[$i]['pcode'].'</td>
<td>'.$resultArr[$i]['pname'].'</td>
<td>'.$resultArr[$i]['pprice'].'</td>
<td>'.$resultArr[$i]['pqty'].'</td>
</tr>';
}
What about something like this?
$message = "";
foreach($_POST['item_cid'] as $key => $value)
{
$cid = mysqli_real_escape_string($connection,$value);
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
for ($i=0; $i < $cid; $i++)
{
$message .= '<tr>
<td>'.$pcode.'</td>
<td>'.$pname.'</td>
<td>'.$pprice.'</td>
<td>'.$pqty.'</td>
</tr>';
}
}