unable to generate automail on daily bases - php

I am unable to generate auto mail on daily bases. The issue is it is not able to generate it automatically. Where as i have a same sort of code which does generates it everyday. With all the same details. The code is exactly same except the database query.
Here is my code:
<?php
session_start();
require("../connect.php");
/* require files for MAIL */
require("class.phpmailer.php");
require("class.smtp.php");
/* require files for MAIL ENDS */
/******** Get the list of audits done in week risk category falls under High Risk and during the previous visit also the location was under High risk category ----mail on every Saturday**********/
$current_date = date('Y-m-d');
//$current_date ='2015-08-22';;
/*$start_time = time() - (6*86400);
$start_dt = date('Y-m-d',$start_time);*/
$pagent_array = array();
$query="Select * from `location_details` ld
Left Join `answer_general_qc` ans_general on ans_general.lid=ld.id
Left Join `audit_general` general on general.qtno = ans_general.qt
Left Join `audit_general_option` general_opt on general_opt.opt_id = ans_general.ans_remark
where ld.completed ='1' and ld.priority != 'qc' and general.qtno ='1' and ans_general.opt = 'no' and
STR_TO_DATE(ld.`date_audited`,'%d-%m-%Y') = '".$current_date."'";
$result=mysql_query($query);
$th_style="border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede";
$td_style="border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff";
$table_result .="<table align='center' rules='all' style='font-family: verdana,arial,sans-serif;font-size:11px;color:#333333;border-width: 1px;border-color: #666666;border-collapse: collapse;' border='1';>
<thead>
<tr>
<th style='".$th_style."'>Sr No</th>
<th style='".$th_style."'>Location Code</th>
<th style='".$th_style."'>Location Name</th>
<th style='".$th_style."'>PAgent</th>
<th style='".$th_style."'>Address 1</th>
<th style='".$th_style."'>Address 2</th>
<th style='".$th_style."'>District</th>
<th style='".$th_style."'>State</th>
<th style='".$th_style."'>Priority</th>
<th style='".$th_style."'>Remark by TO</th>
<th style='".$th_style."'>Remark by TO</th>
</tr>
</thead>
<tbody>";
$sr_no=1;
if(mysql_num_rows($result) != 0)
{
while($row=mysql_fetch_array($result))
{
if($row['option_text'] == "")
{
$option_text="Other";
}
else
{
$option_text=$row['option_text'];
}
$table_result .= "
<tr>
<td style='".$td_style."'>".$sr_no."</td>
<td style='".$td_style."'>".$row['location']."</td>
<td style='".$td_style."'>".$row['agent']."</td>
<td style='".$td_style."'>".$row['pagent']."</td>
<td style='".$td_style."'>".$row['address1']."</td>
<td style='".$td_style."'>".$row['address2']."</td>
<td style='".$td_style."'>".$row['district']."</td>
<td style='".$td_style."'>".$row['state']."</td>
<td style='".$td_style."'>".$row['priority']."</td>
<td style='".$td_style."'>".$option_text."</td>
<td style='".$td_style."'>".$row['qc_remark']."</td>
</tr>";
$sr_no++;
}
}
else
{
$table_result .="<tr><td colspan='9' align='center'>No Locations Found</td></tr>";
}
$table_result .="</tbody>
</table>";
// echo $table_result; exit;
/* Code to send MAIL */
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "host";
$mail->SMTPAuth = true;
//$mail->SMTPSecure = "ssl";
$mail->Port = 25;
$mail->Username = "Username";
$mail->Password = "Password";
$mail->From = "From";
$mail->FromName = "Name";
$mail->AddAddress("Email");
$mail->AddBCC("Email CC");
$body = "Dear All,<br /><br />For the review conducted on ".date('d-m-Y',strtotime($current_date))." in the following locations we have found deviation in question 1.1 (ie Does this location exist exactly at the address provided?) <br /><br /><br /><br />";
$body .= $table_result;
$body .= "<br /><br />Warm Regards <br /><br />
Note : Please do not reply to this email as this is an automated mail generated
";
//end body
$mail->IsHTML(true);
//$mail->Subject = "Ref : RC1/HR/".strtoupper($pa)."/".date('F Y',(time()-(5*86400)));
$mail->Subject = "Ref : Lrr 1.1 deviation";
$mail->Body = $body;
//$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
/* Code to send MAIL Ends */
//mail($to,$subject,$message,$headers);
echo 'Mail sent to '.$pa.'<br /><br />';
/****** END of sending mail **********/
?>

If you want to send mails on a regular or daily basis the ideal way to do that would be to use cron job for sending the mails.By using cron you can specify what application do you want the cron to run on.Also you will be able to specify what time exactly do you want the mail to be sent.
Refer here https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job .
Hope it helps.

Related

php to mysql data retrieval

I am trying to retrieve data from mysql database that has 4 rows. I need to send this as an table in email using php. I have built a script for this, but the issue is the script is not emailing all the rows, its just emailing the last row or if i pass a specific parameter with "where" in db query.
Any help from anyone is appreciated. Thank you in advance.
Attached the db output and php code as well.
<?php
date_default_timezone_set('America/Los_Angeles');
$today = date("j-F-Y g:i:s a"); // March 10, 2001, 5:16 pm
// DB Connect.
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = 'test123#'; // Password
$db_name = 'util'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = "select * from srvr1";
$result = mysqli_query($conn, $sql);
if (!$result) {
die ('SQL Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$File_system = $row[0];
$IP = $row[1];
$Capacity = $row[2];
$Available = $row[3];
$Used = $row[4];
$Percentage = $row[5];
# Compare Percentage and alert.
$subject = "Critical | FH NetApp-NetBackup Space Utilization..!";
$message1 = "
<html>
<body>
<p> Hi Team,<br><br> The Server utilization is <b style='color:red'> critical</b>. Please find the below utilization details.</p>
<table>
<tr>
<th> File_System </th>
<th> IP </th>
<th> Total_capacity </th>
<th> Available_Capacity </th>
<th> Used_Capacity </th>
<th> Percentage </th>
</tr>
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td> $Percentage </td>
</tr>
</table>
<p style='font-size:15px'> Data generated at:<b> $today EST.</b><p>
<p>Regards, <br>
Backup Team. </p>
</body>
</html>";
$headers[] = 'From: Srvr19utilization#util.com'; // Sender's Email
$headers[] = 'Cc: santosh.kowshik20#gmail.com'; // Carbon copy to Sender
$headers[] = 'MIME-Version: 1.0 charset=".$encoding."';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message1, 70);
// Send Mail By PHP Mail Function
mail($to, $subject, $message, implode("\r\n", $headers));
}
}
?>
I have been trying to shuffle around the loop in the code, it did not help.
Try and rearrange your code a little bit. First create the 'top' of the html, then go through all the results and append them to the html and then finish the html.
I haven't tested the code beneath but it should work :-)
<?php
date_default_timezone_set('America/Los_Angeles');
$today = date("j-F-Y g:i:s a"); // March 10, 2001, 5:16 pm
// DB Connect.
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = 'test123#'; // Password
$db_name = 'util'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = "select * from srvr1";
$result = mysqli_query($conn, $sql);
if (!$result) {
die('SQL Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($result) > 0) {
$subject = "Critical | FH NetApp-NetBackup Space Utilization..!";
$message1 = "
<html>
<body>
<p> Hi Team,<br><br> The Server utilization is <b style='color:red'> critical</b>. Please find the below utilization details.</p>
<table>
<tr>
<th> File_System </th>
<th> IP </th>
<th> Total_capacity </th>
<th> Available_Capacity </th>
<th> Used_Capacity </th>
<th> Percentage </th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
$File_system = $row[0];
$IP = $row[1];
$Capacity = $row[2];
$Available = $row[3];
$Used = $row[4];
$Percentage = $row[5];
# Compare Percentage and alert.
$message1 .= "
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td> $Percentage </td>
</tr>";
}
$message1 .= "</table>";
$message1 .= "<p style='font-size:15px'> Data generated at:<b> $today EST.</b><p>
<p>Regards, <br>
Backup Team. </p>
</body>
</html>";
$headers[] = 'From: Srvr19utilization#util.com'; // Sender's Email
$headers[] = 'Cc: santosh.kowshik20#gmail.com'; // Carbon copy to Sender
$headers[] = 'MIME-Version: 1.0 charset=".$encoding."';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message1, 70);
// Send Mail By PHP Mail Function
mail($to, $subject, $message, implode("\r\n", $headers));
}
?>
About conditional formatting
No worries. You can try and use nested ternaries (shorthand for if/else... to keep it short :-))
Example snippet from above code:
...
$Percentage = $row[5];
$color = ($Percentage > 90) ? '#FCE901' : (($Percentage > 85) ? '#FF0000' : '#00E526');
# Compare Percentage and alert.
$message1 .= "
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td style=\"background-color:$color\"> $Percentage </td>
</tr>";
The issue is somewhere on your database end. Based on your var_dump output:
object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(6) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }
You only have 1 result being returned. You should start there. Maybe you're not referencing the table you think you are. Who knows right now, but you php looks fine. Investigate your DB
Your PHP is not fine stubben gave you the answer
<?php
date_default_timezone_set('America/Los_Angeles');
$today = date("j-F-Y g:i:s a"); // March 10, 2001, 5:16 pm
// DB Connect.
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = 'test123#'; // Password
$db_name = 'util'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn)
{
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = "select * from srvr1";
$result = mysqli_query($conn, $sql);
if (!$result)
{
die ('SQL Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$File_system = $row[0];
$IP = $row[1];
$Capacity = $row[2];
$Available = $row[3];
$Used = $row[4];
$Percentage = $row[5];
Above You have a Percentage from 1 Row of Data
Below you use that to decide the eMail subject - only 1 subject per email - so 1 row of data per email
# Compare Percentage and alert.
if($Percentage > 90)
{
$subject = "Critical | FH NetApp-NetBackup Space Utilization..!";
$message1 = "
<html>
<head>
<style>
body,h6 {
font-family: Segoe UI,Helvetica,courier;
}
th {
border: 1px solid black;
border-collapse: collapse;
background-color: #04D1E8;
padding: 10px;
text-align: center;
}
td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
text-align: center;
}
.cri {
background-color: #FF0000;
}
</style>
</head>
<body>
<p> Hi Team,<br><br> The Server utilization is <b style='color:red'> critical</b>. Please find the below utilization details.</p>
<table>
<tr>
<th> File_System </th>
<th> IP </th>
<th> Total_capacity </th>
<th> Available_Capacity </th>
<th> Used_Capacity </th>
<th> Percentage </th>
</tr>
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td class='cri'> $Percentage </td>
</tr>
</table>
<p style='font-size:15px'> Data generated at:<b> $today EST.</b><p>
<p>
Regards, <br>
Backup Team.
</p>
</body>
</html>
";
$headers[] = 'From: Srvr19utilization#util.com'; // Sender's Email
$headers[] = 'Cc: santosh.kowshik20#gmail.com'; // Carbon copy to Sender
$headers[] = 'MIME-Version: 1.0 charset=".$encoding."';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message1, 70);
// Send Mail By PHP Mail Function
mail($to, $subject, $message, implode("\r\n", $headers));
}
else if($Percentage > 85)
{
$subject = "Warning | FH NetApp-NetBackup Space Utilization..!";
$message1 = "
<html>
<head>
<style>
body,h6{
font-family: Segoe UI,Helvetica,courier;
}
th {
border: 1px solid black;
border-collapse: collapse;
background-color: #04D1E8;
padding: 10px;
text-align: center;
}
td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
text-align: center;
}
.war {
background-color: #FCE901;
}
</style>
</head>
<body>
<p> Hi Team,<br><br> The Server utilization is <b style='color:yellow'> above normal</b>. Please find the below utilization details.</p>
<table>
<tr>
<th> File_System </th>
<th> IP </th>
<th> Total_capacity </th>
<th> Available_Capacity </th>
<th> Used_Capacity </th>
<th> Percentage </th>
</tr>
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td class='war'> $Percentage </td>
</tr>
</table>
<p style='font-size:15px'> Data generated at:<b> $today EST.</b></p>
<p>
Regards, <br>
Backup Team.
</p>
</body>
</html>
";
$headers[] = 'From: Srvr19utilization#util.com'; // Sender's Email
$headers[] = 'Cc: santosh.kowshik20#gmail.com'; // Carbon copy to Sender
$headers[] = 'MIME-Version: 1.0 charset=".$encoding."';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message1, 70);
// Send Mail By PHP Mail Function
mail($to, $subject, $message, implode("\r\n", $headers));
}
else
{
$subject = "Normal | FH NetApp-NetBackup Space Utilization..!";
$message1 = "
<html>
<head>
<style>
body,h6{
font-family: Segoe UI,Helvetica,courier;
}
th {
border: 1px solid black;
border-collapse: collapse;
background-color: #04D1E8;
padding: 10px;
text-align: center;
}
td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
text-align: center;
}
.nor {
background-color: #00E526;
}
</style>
</head>
<body>
<p> Hi Team,<br><br> The Server utilization is <b style='color:green'> normal. </b>Please find the below utilization details.</p>
<table>
<tr>
<th> File_System </th>
<th> IP </th>
<th> Total_capacity </th>
<th> Available_Capacity </th>
<th> Used_Capacity </th>
<th> Percentage </th>
</tr>
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td class='nor'> $Percentage </td>
</tr>
</table>
<p style='font-size:15px'> Data generated at:<b> $today EST.</b></p>
<p>
Regards, <br>
Backup Team.
</p>
</body>
</html>
";
$headers[] = 'From: Srvr19utilization#util.com'; // Sender's Email
$headers[] = 'Cc: santosh.kowshik20#gmail.com'; // Carbon copy to Sender
$headers[] = 'MIME-Version: 1.0 charset=".$encoding."';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message1, 70);
// Send Mail By PHP Mail Function
mail($to, $subject, $message, implode("\r\n", $headers));
}
}
}
?>

How to send data in email using HTML table & php

I'm trying to send data from database in the form of a HTML table when user click submit button. I'm able to receive the email but only table received. It doesn't seem database data. I want to email a table with data in database. Here is my code.
<?php
require '../Mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
//$mail->SMTPSecure = 'tls';
//$mail->SMTPAuth = true;
$mail->Host = '';
$mail->Port = ;
$mail->Username = '';
$mail->Password = '';
$mail->setFrom('');
$mail->addAddress('');
$mail->isHTML(true);
$mail->Subject = 'Student data';
$body = '<html>
<head>
<title></title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
text-align: left;
padding: 8px;
color:black
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<?php
$username = "root";
$password = "";
$host = "localhost";
$connector = mysqli_connect("$host,$username,$password");
or die("Unable to connect");
echo "Connections are made successfully::";
$selected = mysqli_select_db("school"," $connector");
or die("Unable to connect");
//execute the SQL query and return records
$result = mysqli_query("SELECT*FROM student ");
?>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>class</th>
<th>address</th>
<th>comment</th>
</tr>
</thead>
<tbody>
<?php
while( $row = mysql_fetch_assoc( $result ) ){?>
<tr>
<td><?php echo $row["id"] ?></td>
<td><?php echo $row["name"]?></td>
<td><?php echo $row["age"] ?></td>
<td><?php echo $row["class"] ?></td>
<td><?php echo $row["address"] ?></td>
<td><?php echo $row["comment"] ?></td>
</tr>
<?php }
?>
</tbody>
</table>
<?php mysql_close($connector); ?>
</body>
</html> ';
$mail->Body = $body;
//send the message, check for errors
if (!$mail->send()) {
echo "ERROR: " . $mail->ErrorInfo;
} else {
echo "SUCCESS";
}
Thanks for everyone, who answer to my question. Here is the working code for my system.
<?php
require '../Mailer/PHPMailerAutoload.php';
$username = "root";
$password = "";
$host = "localhost";
$connector = mysql_connect($host,$username,$password)
or die("Unable to connect");
echo "Connections are made successfully::";
$selected = mysql_select_db("school", $connector)
or die("Unable to connect");
//execute the SQL query and return records
$result= mysql_query("SELECT * FROM student ORDER BY id DESC limit 1");
$mail = new PHPMailer;
$mail->isSMTP();
//$mail->SMTPSecure = 'tls';
//$mail->SMTPAuth = true;
$mail->Host = '';
$mail->Port = ;
$mail->Username = '';
$mail->Password = '';
$mail->setFrom('');
$mail->addAddress('');
$mail->isHTML(true);
$mail->Subject = 'Student Data';
$body = "<html>
<head>
<title>Student Data</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
text-align: left;
padding: 8px;
color:black
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Age</th>
<th>Class</th>
<th>Address</th>
<th>comment</th>
</tr>
</thead>
<tbody>";
while( $row = mysql_fetch_assoc( $result ) ){
$body.= "<tr>
<td>".$row['id']."</td>
<td>".$row['name']."</td>
<td>".$row['age']."</td>
<td>".$row['class']."</td>
<td>".$row['address']."</td>
<td>".$row['comment']."</td>
</tr>";
}
$body.="</tbody></table></body></html>";
?>
<?php mysql_close($connector); ?>
<?php
$mail->Body = $body;
//send the message, check for errors
if (!$mail->send()) {
echo "ERROR: " . $mail->ErrorInfo;
} else {
echo "SUCCESS";
}
?>
Above your mysql connection data ($username, ...) is still a php opening tag.
Your code is all wrong, you're opening php tags inside a php tag.
Also you were using mysqli_ the wrong way, then trying to close with mysql_ .
Here, I fixed it for you:
<?php
require '../Mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
//$mail->SMTPSecure = 'tls';
//$mail->SMTPAuth = true;
$mail->Host = '';
$mail->Port = ;
$mail->Username = '';
$mail->Password = '';
$mail->setFrom('');
$mail->addAddress('');
$mail->isHTML(true);
$mail->Subject = 'Student data';
$body = '<html>
<head>
<title></title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
text-align: left;
padding: 8px;
color:black
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
';
$username = "root";
$password = "";
$host = "localhost";
$connector = mysqli_connect($host,$username,$password, "school");
or die("Unable to connect");
echo "Connections are made successfully::";
//execute the SQL query and return records
$result = mysqli_query($connector, "SELECT*FROM student ");
$body .='
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>class</th>
<th>address</th>
<th>comment</th>
</tr>
</thead>
<tbody>';
while( $row = mysqli_fetch_assoc($connector, $result ) ){
$body .= "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['age']}</td>
<td>{$row['class']}</td>
<td>{$row['address']}</td>
<td>{$row['comment']}</td>
</tr>"
}
$body .='
</tbody>
</table>
</body>
</html> ';
$mail->Body = $body;
//send the message, check for errors
if (!$mail->send()) {
echo "ERROR: " . $mail->ErrorInfo;
} else {
echo "SUCCESS";
}

Unable to send email content using PHPMailer

I am creating an e-commerce website that sends email about order detail after user have checked out. I've succeeded in sending email using PHPMailer. However, the content of email I've sent is being escaped.
How do I ensure that the order detail is being processed properly like the image below?
This is the phpmailer code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>PHPMailer - SMTP test</title>
</head>
<body>
<?php
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set("Asia/Singapore");
require '../PHPMailerAutoload.php';
include ('../test.php');
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "smtp.gmail.com";
//enable this if you are using gmail smtp, for mandrill app it is not required
$mail->SMTPSecure = 'ssl';
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 465;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "GMAIL.COM";
//Password to use for SMTP authentication
$mail->Password = "PASSWORD";
//Set who the message is to be sent from
$mail->setFrom('popo#shop.com', 'POPO ECOMMERCE');
//Set an alternative reply-to address
$mail->addReplyTo('popo#shop.com', 'POPO ECOMMERCE');
//Set who the message is to be sent to
$mail->addAddress($email, $user);
//Set the subject line
$mail->Subject = 'Order Details';
//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('order.php'), dirname(__FILE__));
//Replace the plain text body with one created manually
//$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
$mail->XMailer = ' ';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
</body>
</html>
Message code:
<?php
include("../include/db.php");
$user= $_SESSION['id'];
?>
<?php
echo
"<div style='width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 15px;'>
<h1>Order Details</h1>
";
echo
"<p>Dear <b style='color:blue;'>$user</b>, you have ordered the following products from our website: popo.
Below are the details of your order. We will be shipping the products to your address in two weeks.
<br><br>
Thank you for using POPO.
<Br><br><br>
Order Details: <br></p>";
echo '
<table width = "1093" align="center" bgcolor="silver">
<tr align="center">
<th>S.N</th>
<th>Product ID</th>
<th>Invoice ID</th>
<th>QTY</th>
</tr>';
$get_pro =$db->prepare( 'select Product_ID,invoice_id,qty from orders where userid = ?');
$get_pro->bind_param('s',$user);
$get_pro->execute();
$get_pro->bind_result($pro_title,$pro_id,$pro_qty);
$i =0 ;
while ($get_pro->fetch())
{
$i++;
?>
<?php
echo "
<tr align='center'>
<td> $i</td>
<td> $pro_title</td>
<td> $pro_id</td>
<td>$pro_qty</td>
</tr>";
?>
<?php } ?>
<?php echo "</table>"?>
file_get_content() does not execute php script. You need to replace:
$mail->msgHTML(file_get_contents('order.php'), dirname(__FILE__));
by
ob_start();
include "order.php";
$message = ob_get_clean();
$mail->msgHTML($message);
dont load the order.php with file_get_contents() cause this will not execute the php code!
include the file like this:
ob_start();
include("order.php");
$message = ob_get_contents();
ob_end();
$mail->msgHTML($message);
Try replacing the messege code to this:
<?php
include("../include/db.php");
$user = $_SESSION['id'];
echo "<div style='width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 15px;'>
<h1>Order Details</h1>";
echo "<p>Dear <b style='color:blue;'>$user</b>, you have ordered the following products from our website: popo.
Below are the details of your order. We will be shipping the products to your address in two weeks.
<br>
<br>
Thank you for using POPO.
<Br><br><br>
Order Details: <br></p>";
echo '
<table width = "1093" align="center" bgcolor="silver">
<tr align="center">
<th>S.N</th>
<th>Product ID</th>
<th>Invoice ID</th>
<th>QTY</th>
</tr>';
$get_pro = $db->prepare('select Product_ID,invoice_id,qty from orders where userid = ?');
$get_pro->bind_param('s',$user);
$get_pro->execute();
$get_pro->bind_result($pro_title,$pro_id,$pro_qty);
$i = 0;
while ($get_pro->fetch())
{ $i++;
echo "<tr align='center'>
<td> $i</td>
<td> $pro_title</td>
<td> $pro_id</td>
<td>$pro_qty</td>
</tr>";
break;
}
echo "</table>";
?>
And on the other file:
$mail->msgHTML(file_get_contents('order.php'), dirname(__FILE__));
To:
ob_start();
include("order.php");
$message = ob_get_contents();
ob_end();
$mail->msgHTML($message);

PHPMailer MySQLi multiple email addresses

I am at the end of my rope and would really really appreciate any help you could spare...
I have the following code and although it works on an individual basis, I can for the life of me not make it work so that all email addresses are sent at the same time using PHPMailer.
I have scoured StackOverflow for the past few months, trying an exhaustive amount of combinations without success.
There are a number of discussions on this forum and although I have tried all the solutions on here, I can still not make it work. If I offend anyone by potentially duplicating the question, please accept my apologies in advance.
<?php
// Script Error Reporting
//error_reporting(0);
// Require the form_functions to process the form
require('databaseConnect.php');
// Require the Email Class Functions
require("mailApp/class.phpmailer.php");
require("mailApp/class.smtp.php");
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPKeepAlive=true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->setFrom("No_Reply#girrawaagames.com", "Girrawaa Games"); // Valid email address from sender and Company name. Only Company name will be displayed
$mail->Subject='CASH Trader | The Spirit Stone'; // This adds the subject title in the subject line field
// Create a connection to MySQL and the database:
$con = mysqli_connect($hostname, $username, $password, $database);
// Check if the connection is active:
if(!$con) {
header('Location: alternate.php');
}
$result = mysqli_query($con, "SELECT fname, email FROM emails WHERE condition = 'condition'");
/* fetch associative array */
while ($row = $result->fetch_array()) {
$user['fname'][] = $row["fname"];
$user['email'][] = $row["email"];
}
$mail->AddAddress($user['email']);
$mail->Body="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>CASH Trader</title>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />
</head>
<body yahoo bgcolor=\"#ccffff\" style=\"margin:0; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px;\">
<table align=\"center\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse\">
<tr>
<td style=\"padding-top:20px; padding-right:0px; padding-bottom:30px; padding-left:0px; color:#153643; font-size:28px; font-weight:bold; font-family:Arial, Helvetica, sans-serif;\">
<table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\">
<tr>
<td class=\"header\" align=\"center\" bgcolor=\"#333333\" style=\"padding-top:10px; padding-right:10px; padding-bottom:10px; padding-left:10px; color:#153643; font-size:28px; font-weight:bold; font-family:Arial, Helvetica, sans-serif;\">
<img src=\"http://www.girrawaagames.com/img/logo.jpg\" style=\"color:#FFFFFF\" alt=\"Cash Trader Logo\" style=\"display:block; max-width:100%; height:auto;\" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td bgcolor=\"#ffffff\" style=\"padding-top:40px; padding-right:30px; padding-bottom:20px; padding-left:30px;\">
<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">
<tr>
<td align=\"center\" style=\"color:#153643; font-family:Arial, Helvetica, sans-serif; font-size:24px;\">
<b>Hi " . $user['fname'] . "</b>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>";
print_r($user['fname']);
print_r($user['email']);
if ($mail->send()) {
$updateCampaign = "UPDATE emails SET column = 'value' WHERE email = '" . mysqli_real_escape_string($row['email']) . "'";
$results = mysqli_query($con, $updateCampaign);
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
mysqli_free_result($result);
mysqli_close($con);
You need to concatenate the $useremail for it to have multiple emails.
$userEmail = '';
foreach($rows as $row) {
$userFname = $row["fname"];
$userEmail .= $row["email"] . ',';
}
It would probably be easier to pair these in an array..
foreach($rows as $row) {
$user['fname'][] = $row["fname"];
$user['email'][] = $row["email"];
}
Then you don't need the explode function later.
....
or better yet set it in the while loop, dont need foreach at all.
while($row = $result->fetch_array()){
$user['fname'][] = $row["fname"];
$user['email'][] = $row["email"];
}
Update:
<?php
// Script Error Reporting
//error_reporting(0);
// Require the form_functions to process the form
require('databaseConnect.php');
// Require the Email Class Functions
require("mailApp/class.phpmailer.php");
require("mailApp/class.smtp.php");
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPKeepAlive=true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->setFrom("No_Reply#girrawaagames.com", "Girrawaa Games"); // Valid email address from sender and Company name. Only Company name will be displayed
$mail->Subject='CASH Trader | The Spirit Stone'; // This adds the subject title in the subject line field
// Create a connection to MySQL and the database:
$con = mysqli_connect($hostname, $username, $password, $database);
// Check if the connection is active:
if(!$con) {
header('Location: alternate.php');
exit();
}
$result = mysqli_query($con, "SELECT fname, email FROM emails WHERE condition = 'condition'");
/* fetch associative array */
while ($row = $result->fetch_array()) {
$user['fname'][] = $row["fname"];
$user['email'][] = $row["email"];
}
foreach($user['email'] as $key => $email) {
$mail->AddAddress($email);
$mail->Body="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>CASH Trader</title>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />
</head>
<body yahoo bgcolor=\"#ccffff\" style=\"margin:0; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px;\">
<table align=\"center\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse\">
<tr>
<td style=\"padding-top:20px; padding-right:0px; padding-bottom:30px; padding-left:0px; color:#153643; font-size:28px; font-weight:bold; font-family:Arial, Helvetica, sans-serif;\">
<table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\">
<tr>
<td class=\"header\" align=\"center\" bgcolor=\"#333333\" style=\"padding-top:10px; padding-right:10px; padding-bottom:10px; padding-left:10px; color:#153643; font-size:28px; font-weight:bold; font-family:Arial, Helvetica, sans-serif;\">
<img src=\"http://www.girrawaagames.com/img/logo.jpg\" style=\"color:#FFFFFF\" alt=\"Cash Trader Logo\" style=\"display:block; max-width:100%; height:auto;\" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td bgcolor=\"#ffffff\" style=\"padding-top:40px; padding-right:30px; padding-bottom:20px; padding-left:30px;\">
<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">
<tr>
<td align=\"center\" style=\"color:#153643; font-family:Arial, Helvetica, sans-serif; font-size:24px;\">
<b>Hi " . $user['fname'][$key] . "</b>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>";
if ($mail->send()) {
$updateCampaign = "UPDATE emails SET column = 'value' WHERE email = '" . mysqli_real_escape_string($row['email']) . "'";
$results = mysqli_query($con, $updateCampaign);
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
mysqli_free_result($result);
mysqli_close($con);
}
You say you've looked everywhere... apart from code you already have! There is a mailing list example provided with PHPMailer that does exactly what you ask, correctly and efficiently.
In your code you're trying to send one message to 50 people, not 50 to 50, and it would also expose all addresses to all recipients, so this is generally a bad idea.
You've based your code on an obsolete example and are probably using an old version of PHPMailer, so get the latest.

Mailer function does not work for gmail [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
if($sql)
{
require("master/PHPMailerAutoload.php");
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "mail.php.net";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "krajesh#php.net";
$mail->Password = "password";
$mail->SetFrom("krajesh#php.net");
$mail->Subject = "subject";
$mail->Body = "<table cellpadding='0' cellspacing='0' border='0' bgcolor='#006699' style='border:solid 10px #006699; width:550px;'>
<tr bgcolor='#006699' height='25'>
<td><img src='logo.jpg' border='0' width='200' height='60' /></td>
</tr>
<tr bgcolor='#FFFFFF'><td> </td></tr>
<tr bgcolor='#FFFFFF' height='30'>
<td valign='top' style='font-family:Arial; font-size:12px; line-height:18px; text-decoration:none; color:#000000; padding-left:20px;'><b> Login details from $website_name </b></td></tr>
<tr bgcolor='#FFFFFF' height='35'>
<td style='padding-left:20px; font-family:Arial; font-size:11px; line-height:18px; text-decoration:none; color:#000000;'>Username : $email </td>
</tr>
<tr bgcolor='#FFFFFF' height='35'>
<td style='padding-left:20px; font-family:Arial; font-size:11px; line-height:18px; text-decoration:none; color:#000000;'>Password :$password</td>
</tr>
<tr bgcolor='#FFFFFF' height='35'>
<td style='padding-left:20px; font-family:Arial; font-size:11px; line-height:18px; text-decoration:none; color:#000000;'><a href='$website_url/index.php?activate=".$actvateid."' style='font-family:Arial; font-size:11px; font-weight:bold; text-decoration:none; color:#2200CC;'>Click Here</a> to activate your account</td>
</tr>
</table>";
$mail->AddAddress($email);
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "<script> window.location='index.php?sendsus'; </script>";
exit;
}
}
Did I make a mistake in the code or do I have to change the mailer function itself?
The mail function is working locally, but not working for gmail.. I also tried live but gmail is not working..
You are using wrong host and port number use this code
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->SMTPSecure = "tls";

Categories