Sending a mail in PHP with Linux - php

I have a program which works perfectly to send a mail in PHP using Windows, but now I want to send it using a cronjob in Linux to execute it everyday. What do I need to do to work in Linux? Do I need to configure the php.ini file, sendmail etc. like I did in Windows?
Here is the program I've used for sending the email.
<?php
ini_set('max_execution_time', 600);
require 'class.phpmailer.php';
$host = ".....";
$user = "....";
$pass = ".....";
$db = "......";
$con1 = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query1 = "select commands.author, users.badge_no
from commands
inner join users
on commands.author=users.username";
$rs1 = pg_query($con1, $query1) or die("Cannot execute query: $query\n");
$query = "SELECT distinct commands_details.delivery_date,commands_details.command_no,commands.author,commands_details.name
FROM commands_details
inner join commands
on commands_details.command_no=cast(commands.id as varchar)";
$rs = pg_query($con1, $query) or die("Cannot execute query: $query\n");
$nume=array();
$mail1=array();
while ($row = pg_fetch_row($rs1)){
$nume[]=$row[0];
$mail1[]=$row[1];
}
$arrlength = count($nume);
$var_data='2016-06-19';
$mail_trimitere=array();
while ($row = pg_fetch_row($rs)) {
if(strpos($row[0], $var_data) !== false){
for($j=0;$j<$arrlength;$j++){
if($row[2]===$nume[$j]){
$mail_trimitere[0]=$mail1[$j];
echo $mail_trimitere[0];
break;
}
}
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->Username = "......";
$mail->Password = "........";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true;
$mail->From = "......";
$mail->FromName = ".......";
$mail->addAddress(".........","robert");
$mail->Subject = "Testing PHPMailer with localhost";
$mail->Body = 'urmeaza sa primiti maine comanda cu numarul '.' '.$row[1].' '.'produs'.' '. $row[3].' '. 'in data de '.' '.$row[0];
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
}
}
pg_close($con1);
?>

Related

PHP SMTP Mail script not working

I'm coding a php smtp mail script to send a mail to my users when they lose their password. However it's not working.
The processor always returns:
Message could not be sent...
I've tried it with Gmail smtp and I'm getting the same results.
Can you help? There are two files, the form, and the processor.
Below are the codes:
form:
<html>
<head>
<meta name = 'viewport' content = 'width = device-width, initial-scale = 1.0, maximum-scale = 4.0, user-scalable = yes'>
<link rel = 'stylesheet' href = 'style.css' type = 'text/css'>
<title>Reset Password</title>
</head>
<?php
$db = new PDO('mysql:host=host;dbname=db;charset=utf8', 'user', 'pass');
$sql = $db->query('select id from posts order by id desc');
$row = $sql->fetch(PDO::FETCH_ASSOC);
echo "<a href = 'browse.php?page=".$row['id']."'>Browse</a> <a href = 'index.php'>Home</a>";
echo "<hr>";
echo '<form name = "forgot-pass" action = "reset-pass-notif.php" method = "post">
<label><em>Input your registered email address</em></label><br>
<input type = "text" name = "email"><br>
<em>Enter Image Text:</em><img src="captcha.php" /><br />
<input name="captcha" type="text" /><br>
<input type = "submit" name = "submit" value = "Send Reset-Password Link">
</form>
<hr>
Browse Home';
?>
</html>
processor:
<html>
<head>
<meta name = 'viewport' content = 'width = device-width, initial-scale = 1.0, maximum-scale = 4.0, user-scalable = yes'>
<link rel = 'stylesheet' href = 'style.css' type = 'text/css'>
<title>Reset Password Notification</title>
</head>
<?php
error_reporting(E_ALL);
session_start();
$db = new PDO('mysql:host=host;dbname=db;charset=utf8', 'user', 'pass');
$sql0 = $db->query('select id from posts order by id desc limit 1');
$row0 = $sql0->fetch(PDO::FETCH_ASSOC);
echo 'Browse Home';
echo '<hr>';
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$sql = $db->prepare('select * from users where email = :email');
$sql->bindParam(':email', $email);
$sql->execute();
$sql->setFetchMode(PDO::FETCH_ASSOC);
$row = $sql->fetch();
$username = $row['username'];
$user_check = $row['user_hash'];
$subject = 'Reset your Password';
$link = 'http://bquotes.xyz/reset-pass-land.php?username='.$row['username'].'&user_check='.$row['user_hash'].'';
$message = 'Reset your password here: '.$link.' If you cannot click on the link, copy it and paste in your browser address bar';
$sql = $db->prepare('select email from users where email = :email');
$sql->bindParam(':email', $email);
$sql->execute();
$sql->setFetchMode(PDO::FETCH_ASSOC);
$row = $sql->fetch();
//require_once ('class.phpmailer.php');
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.domain.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#domain.com'; // SMTP username
$mail->Password = 'pass'; // SMTP password
//$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('user#domain.com', 'BQuotes Webmaster');
//$mail->addAddress($email); // Add a recipient
/*$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
$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
$mail->Subject = $subject;
$mail->Body = $message;
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
/*if(!$mail->send()) {
//echo '<em>Message could not be sent. Mailer Error:</em> ', "<em>", $mail->ErrorInfo, "</em>";
echo '<span class = "red"><em>Message could not be sent. You have one or more invalid fields.</em></span>';
} else {
echo '<span class = "green"><em>Message has been sent. Please check your Spam folders if not in Inbox by 10 minutes.</em></span>';
}*/
if (($email)&&($username)&&!empty($_POST['captcha'])&&($_POST['captcha']==$_SESSION['code'])&&($mail->send())){
echo '<span class = "green"><em>Message has been sent. Please check your Spam folders if not in Inbox by 10 minutes.</em></span>';
}
else {echo '<span class = "red"><em>Message could not be sent. You have one or more invalid fields.</em></span>';
}
echo "<hr>";
echo 'Browse Home';
?>
</html>
Thanks!
The correct setting for PHPMailer:
<?php
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Username = "user#domain.com";
$mail->Password = "xxxx";
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.domain.com";
$mail->Port = "465";
$mail->setFrom('from#domain.com', 'John Doe');
$mail->addReplyTo('from#domain.com', 'John Doe');
$mail->AddAddress("mailto#otherdomain.com", "Jane Smith");
$mail->CharSet = 'UTF-8';
$mail->IsHTML(true);
$mail->Subject = 'Bla bla or from DB';
$mail->Body = 'Here come the content...';
if (!$mail->send()) {
echo 'Error: ' . $mail->ErrorInfo;
exit;
}
?>
Please use this code .make sure you have given permission in Mail account from you want to send mail.
My Account->Sign-in & security->Allow less secure apps: OFF
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = false;
$mail->isSMTP();
$mail->Host = 'smtp.live.com';
$mail->SMTPAuth = true;
$mail->Username = 'mail#gmail.com';
$mail->Password = 'Password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom($details['from'], $details['from']);
if(is_array($details['to'])){
foreach ($details['to'] as $key => $value) {
$mail->addAddress($value['email'], $value['name']);
}
}else{
$mail->addAddress($details['to'], isset($details['name'])?:$details['to']);
}
$mail->isHTML(true);
$mail->Subject =$details['subject'];
$mail->Body =$details['body'];
$mail->send();
Are you running this on localhost? Try Putting off your antivirus for some time. Antivirus tends to block email sending from localhost at times

Unable to fetch data from table

I am testing a form that asks for a users email and then sends him his name,surname and cellphone number. Now everything is working. It selects the user depending on the email entered. It sends the email.
The only issue I am having is how do I insert the data from the table into the email thats sending to him?
Eg.$mail->Body = "Your company details are: " Name,Surname,Cellphone;
thats the issue I am currently facing. My full code is below.
I am still quite new at PHP so if this is a general/common error, then I apologise.
<?php
error_reporting(1);
ini_set('error_reporting', E_ALL);
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="****"; // Mysql password
$db_name="Username"; // Database name
$tbl_name="Name"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password, $db_name);
// Define $username and $password
$username=$_POST['user_name'];
$sql="SELECT * FROM $tbl_name WHERE Name='$username'";
$result=mysqli_query($conn, $sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if ($count > 0)
{
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "****"; // SMTP server // enables SMTP debug information
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "****"; // sets the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "****"; // SMTP account username
$mail->Password = "****"; // SMTP account password
$mail->From = "Test";
$mail->FromName = "Test";
$mail->AddAddress($username, "");
$mail->isHTML(true);
$mail->Subject = 'Out Of Office Password';
$mail->Body = "Your Out Of Office password: ";
if(!$mail->Send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit();
}
else
{
echo 'Email Sent Successfully!';
}
}
?>
The form:
<center>
<html>
<head>
<title>User Information</title>
</head>
<body>
<form action="check-user.php" method="POST">
<h3>User Information</h3>
Email: <input type="text" name="user_name"><br>
<input type="submit" name="submit" value="Send Info">
</form>
</body>
</html>
</center>
First make your connection valid
$conn = mysqli_connect($host, $username, $password, $db_name)
// if u get connection valid message delete this if statement this is just for testing your connection
if ($conn) {
echo 'connection valid';
} else {
echo 'connection invalid ' . mysqli_error($conn);
}
And u don't need this
echo "Connected to MySQL<br />";
mysqli_select_db("$db_name") or die(mysqli_error());
echo "Connected to Database<br />";
Change this line
$result=mysqli_query($conn, $sql);
And this one
if ($count > 0) {
And because u new to php, i think u need atleast learn how to connect to database, check for error_reporting, get/update/insert/delete data into database.
And my opinion is if u are starting to learn use PDO with prepared statements because it safe. This mysqli without escaping will get u trouble with security.
EDIT:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="****"; // Mysql password
$db_name="Username"; // Database name
$tbl_name="Name"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password, $db_name) or die(mysqli_error($conn));
if (isset($_POST['submit']))
{
// Define $username
$username = $_POST['user_name'];
$sql = "SELECT * FROM $tbl_name WHERE Name='$username'";
$result = mysqli_query($conn, $sql);
// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);
if ($count > 0 )
{
// get data from user
$data = mysqli_fetch_array($result, MYSQLI_ASSOC);
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "****"; // SMTP server // enables SMTP debug information
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "****"; // sets the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "****"; // SMTP account username
$mail->Password = "****"; // SMTP account password
$mail->From = "Test";
$mail->FromName = "Test";
$mail->AddAddress($username, "");
$mail->isHTML(true);
$mail->Subject = 'Your Company Details';
$mail->Body = "Your company details are: Name: = " . $data['Name'] . ", Surname: " . $data['Surname'] . ", Cellphone: " . $data['Cellphone'];
if(!$mail->Send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit();
}
else
{
echo 'Email Sent Successfully!';
}
}
ob_end_flush();
?>

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

How to send multiple mails in PHP?

I'm trying to send email from a database. I get email from the databse and send message to email I get from database.
My code is working good, but I have problem the sending mail - it is only sent for the first one.
include("config.php");
include ("library.php");
include ("classes/class.phpmailer.php");
$sql = "select * from Table ";
$result = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($result)) {
if ($row['Date_Registry'] == date("Y-m-d") ){
$sql= "select * from write_message where ID='$m'";
$result = mysql_query($sql, $conn);
$row = mysql_fetch_array($result);
$email= $row['EMAIL'];
$masg = $row['Write_message'];
$Message_name = $row['Message_name'];
$email = $email;
$mail = new PHPMailer; // call the class
$mail->IsSMTP();
$mail->Host = SMTP_HOST; //Hostname of the mail server
$mail->Port = SMTP_PORT; //Port of the SMTP like to be 25, 80, 465 or 587
$mail->SMTPAuth = true; //Whether to use SMTP authentication
$mail->Username = SMTP_UNAME; //Username for SMTP authentication any valid email created in your domain
$mail->Password = SMTP_PWORD; //Password for SMTP authentication
$mail->SetFrom(SMTP_UNAME, "Helli"); //From address of the mail
// put your while loop here like below,
$mail->Subject = $Message_name; //Subject od your mail
$mail->AddAddress($email); //To address who will receive this email
}
}
Just add the function clearAddress above the AddAddress function (as below) and it will work.
include("config.php");
include ("library.php");
include ("classes/class.phpmailer.php");
$sql = "select * from Table ";
$result = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($result)) {
if ($row['Date_Registry'] == date("Y-m-d") ){
$sql= "select * from write_message where ID='$m'";
$result = mysql_query($sql, $conn);
$row = mysql_fetch_array($result);
$email= $row['EMAIL'];
$masg = $row['Write_message'];
$Message_name = $row['Message_name'];
$email = $email;
$mail = new PHPMailer; // call the class
$mail->IsSMTP();
$mail->Host = SMTP_HOST; //Hostname of the mail server
$mail->Port = SMTP_PORT; //Port of the SMTP like to be 25, 80, 465 or 587
$mail->SMTPAuth = true; //Whether to use SMTP authentication
$mail->Username = SMTP_UNAME; //Username for SMTP authentication any valid email created in your domain
$mail->Password = SMTP_PWORD; //Password for SMTP authentication
$mail->SetFrom(SMTP_UNAME, "Helli"); //From address of the mail
// put your while loop here like below,
$mail->Subject = $Message_name; //Subject od your mail
$this->phpMailerObj->clearAddresses(); //Clear Addresses
$mail->AddAddress($email); //To address who will receive this email
$this->phpMailerObj->Body = "body";
$this->phpMailerObj->msgHTML("Message");
try {
$this->phpMailerObj->Send();
return;
} catch (Exception $exc) {
return $error['error'] = "Email cound not be sent";
}
}
}

How to retrieve more than one data in email?

I have a table named 'laptop' and a column inside the table named 'Lap_War_Expiry'. I need to send an email to user when the warranty of the laptop is going to expire soon. For your information, there is more than one warranty that will expired in a day. But the code below is only send the same data from table 'laptop'. Why is that happened and what I have to add in the code so that the email send will retrieve two or more data from database ?
This is my coding for sending the email :
<?php
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com'; // "ssl://smtp.gmail.com" didn't worked
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
// ======== get database data ==================
$link = mysql_connect("localhost","root","");
$database="master_inventory";
mysql_select_db ($database,$link) OR die ("Could not open $database" );
$query = 'SELECT Lap_PC_Name, Lap_War_Expiry FROM laptop'; //xyz is id of desired user
name.
$result1 = mysql_query($query);
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
}
$mail->Username = "email#gmail.com";
$mail->Password = "somepassword";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true;
$mail->From = "email#gmail.com";
$mail->FromName = "AMS";
$mail->addAddress("emailaddress","AMS");
$mail->Subject = "Notification on warranty expiry";
$mail->Body = "Dear Madam,<br/><br />The licensed for the following PC will expired
in less than one month.<br /><br /> PC Name : ".$Lap_PC_Name. "<br />Date of expired :"
.$Lap_War_Expiry;
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
?>
You need to move everything from below your while loop into it.
EDIT
Change
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
}
to
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
$mail->Username = "email#gmail.com";
$mail->Password = "somepassword";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true;
$mail->From = "email#gmail.com";
$mail->FromName = "AMS";
$mail->addAddress("emailaddress","AMS");
$mail->Subject = "Notification on warranty expiry";
$mail->Body = "Dear Madam,<br/><br />The licensed for the following PC will expired
in less than one month.<br /><br /> PC Name : ".$Lap_PC_Name. "<br />Date of expired :"
.$Lap_War_Expiry;
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
}

Categories