PHPMailer not getting executed via CRON, but working via the browser. What can be the problem? - php

I am trying to run PHPMailer via cron but for some reason, only the part for the token update is executed after that nothing is executed. But, if I run it via browser everything works fine. Any reason why this happens?
require_once(dirname(__DIR__)."/test/mail/PHPMailer.php");
require_once(dirname(__DIR__)."/test/mail/SMTP.php");
require_once(dirname(__DIR__)."/test/mail/Exception.php");
require_once(dirname(__DIR__)."/test/db/conn.php");
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
Only this part of the code is executed via cron, but in the browser, everything is executed even after this part of the code.
$sql = "SELECT * FROM customers WHERE mail_status = 0 LIMIT 100";
$results = $conn->query($sql);
while ($row = $results->fetch_assoc()) {
$salt = rand(5, 20);
$token = sha1($salt . sha1($salt . sha1(rand(5, 20))));
$insert = "UPDATE customers SET token = '" . $token . "' WHERE id = '" . (int)$row['id'] . "'";
$conn->query($insert);
}
This part is not executed via cron:
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true;
$mail->Port = 25;
$mail->Username = 'example#example.com';
$mail->Password = 'example';
$mail->setFrom('example#example.com', 'example');
$mail->isHTML(true);
$mail->Subject = 'example';
$mail->AltBody = 'example';
$mail->AddEmbeddedImage('image/3.jpg', 'logo', '3.jpg');
$result = $conn->query($sql);
foreach ($result as $row) {
$encoded_user_id = base64_encode($row['id']);
$link = "http://www.example.com/test/unsubscribe.php?id=". $encoded_user_id ."&token=".$row['token'];
$body = file_get_contents('contents.html');
$body .= '<div><a style="text-decoration: none;color:#38aa20;" href="'.$link.'">unsubscribe</a></div>';
$mail->msgHTML($body);
try {
$mail->addAddress($row['email']);
} catch (Exception $e) {
echo 'Invalid address skipped: ' . htmlspecialchars($row['email']) . '<br>';
continue;
}
try {
$mail->send();
echo 'Message sent to :' . htmlspecialchars($row['email']) . '<br>';
$update = "UPDATE customers SET mail_status = 1 WHERE id= '" . (int)$row['id'] . "'";
$conn->query($update);
} catch (Exception $e) {
echo 'Mailer Error (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
$mail->smtp->reset();
}
$mail->clearAddresses();
}
$conn->close();
UPDATE
Problem solved

Problem was with image , must be set full path to the image
this cause error
$mail->AddEmbeddedImage('image/3.jpg', 'logo', '3.jpg');
Fix
$mail->AddEmbeddedImage(dirname(__DIR__).'/test/image/3.jpg', 'logo', '3.jpg');

Set full path to these files
require_once(dirname(__DIR__)."/test/mail/PHPMailer.php");
require_once(dirname(__DIR__)."/test/mail/SMTP.php");
require_once(dirname(__DIR__)."/test/mail/Exception.php");
require_once(dirname(__DIR__)."/test/db/conn.php");
like this
require_once("/var/www/_my_path_/test/mail/PHPMailer.php");

Related

Get data for mail body: phpmailer

I'd like to send mails via phpmailer and I'd like to get the name from the database for mail body with looping, but my code doesn't work. It keeps on getting the same name for every single mail. Here's my code:
<?php //Library require("phpmailer/classes/class.phpmailer.php");
//Database
$server = "localhost";
$username = "mydatabase_admin";
$password = "localadmin123";
$database = "mydatabase";
//Connect to database
$dbConnection = mysqli_connect($server, $username, $password, $database);
//Check connection
if ($dbConnection -> connect_error) {
echo "Connection Failed";
die ($dbConnection -> connect_error);
}
//Select database and data
$sql = "SELECT * FROM userdata";
$result = $dbConnection -> query($sql);
//Mailing
//Sender information
$mail = new PHPMailer();
$mail->SMTPDebug = 0;
//Use SMTP
$mail->IsSMTP();
$mail->SMTPAuth = true;
//SMTP Server
$mail->Host = "ssl://smtp.gmail.com";
$mail->Port = 465;
//SMTP Account
$mail->Username = "my_mail#gmail.com";
$mail->Password = "********";
//Automated Mail
$mail->SetFrom('tphp43598#gmail.com', 'Admin');
//Recipient info
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc())
{
$mail->AddAddress($row["Email"]);
$mail->Subject = "Product Review Reminder";
$mail->Body = "Hi ". $row["Full Name"] .",". "\n \nJust a reminder that you need to review the product coded ". $row["Product Handled"] . ".\n" . "Thank You";
}
}
//Output shown if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo "\n" . 'Message has been sent.';
} ?>
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc())
{
$mail->AddAddress($row["Email"]);
$mail->Subject = "Product Review Reminder";
$mail->Body = "Hi ". $row["Full Name"] .",". "\n \nJust a reminder that you need to review the product coded ". $row["Product Handled"] . ".\n" . "Thank You";
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo "\n" . 'Message has been sent.';
}
}
}
You are calling sendmail() function outside while loop you are getting name variable whichever is last record. keep inside while loop.
Or if you need to track each individual mail send status then keep array of status. Keep pushing message into status array.

warning in base64_encode of in phpmailer class

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.

How to send email based on two tables after insert query?

I'm trying to send an email update to users from the candidates_table but the content of the email comes from the jobs_list table. Please see my attempt below, I'm using PHPmailer and I'm getting no errors. The script below is the handling script for a form.
The data from the jobs_list is being displayed, however, the candidates_table data is not.
This is just below the insert statement:
UPDATE:
$vac_last_id = $dbh->lastInsertId();
echo $vac_last_id;
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE id=:id");
$sql->bindValue(':id', $vac_last_id, PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
while($row = $sql->fetch()) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = '';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port =;
$mail->Username = '';
$mail->Password = '';
$mail->setFrom('', '- Vacancies');
$mail->addReplyTo('', '- Vacancies');
$mail->Subject = "";
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
$mail->Body = 'THE BODY...';
//msgHTML also sets AltBody, but if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer';
//Connect to the database and select the recipients from your mailing list that have not yet been sent to
//You'll need to alter this to match your database
$mysql = $dbh->prepare("SELECT * FROM candidates_table WHERE receive_email = 2");
if ($mysql->execute()) {
$mysql->setFetchMode(PDO::FETCH_ASSOC);
}
foreach ($mysql as $row) { //This iterator syntax only works in PHP 5.4+
$mail->addAddress($row['email_address'], $row['full_name']);
if (!$mail->send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email_address"]) . ') ' . $mail->ErrorInfo . '<br />';
break; //Abandon sending
} else {
echo "Message sent to :" . $row['full_name'] . ' (' . str_replace("#", "#", $row['email_address']) . ')<br />';
//Mark it as sent in the DB
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
}
}
Insert Job List in job_listing table. Find, current job_listing table id. Fetch it again and find all candidates to send email.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require 'PHPMailer/PHPMailerAutoload.php';
include 'db_connect.php';
$contact_name = $_POST['contact_name'];
$latest_job_id = 0;
$stmt = $dbh->prepare("INSERT INTO jobs_list (jobTitle, company_name, job_details, salary_info, salary_extra, apply_link, company_email, company_phone, TimeStamp) VALUES (:jobTitle, :company_name, :job_details, :salary_info, :salary_extra, :apply_link, :company_email, :company_phone, NOW())");
$stmt->bindParam(':jobTitle', $_POST['jobTitle'], PDO::PARAM_STR);
$stmt->bindParam(':company_name', $_POST['company_name'], PDO::PARAM_STR);
$stmt->bindParam(':job_details', $_POST['job_details'], PDO::PARAM_STR);
$stmt->bindParam(':salary_info', $_POST['salary_info'], PDO::PARAM_STR);
$stmt->bindParam(':salary_extra', $_POST['salary_extra'], PDO::PARAM_STR);
$stmt->bindParam(':apply_link', $_POST['apply_link'], PDO::PARAM_STR);
$stmt->bindParam(':company_email', $_POST['company_email'], PDO::PARAM_STR);
$stmt->bindParam(':company_phone', $_POST['company_phone'], PDO::PARAM_STR);
$stmt->execute();
$latest_job_id = $dbh->lastInsertId(); //#Nana Comments: Get latest Job Listing ID
if($latest_job_id > 0){
/*#Nana Comments: If Inserted Successfully, '$latest_job_id' will be greater than 0.*/
$mail_error_text = ""; //#Nana Comments: If email not sent, then it will store the email address
/*#Nana Comments: Select recent job listing details.*/
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE id = :id LIMIT 0, 1");
$sql->bindParam(':id', $latest_job_id);
if ($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = ''; // Enable TLS encryption, `ssl` also accepted
$mail->Port = ''; // TCP port to connect to
$mail->setFrom('', 'sender');
while ($row = $sql->fetch()) {
$new_company_email = trim($row['company_email']);
$new_company_name = trim($row['company_name']);
/*#Nana Comments: Select all candidates and send email */
$load_candidate = $dbh->prepare("SELECT * FROM candidates_table");
if ($load_candidate->execute()) {
$load_candidate->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $load_candidate->fetch()) {
$mail->addAddress($row['email_address']); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New Vacancy';
$mail->Body = 'mail body in here';
$mail->AltBody = '';
if(!$mail->send()){
$mail_error_text .= "Mailer Error (" . str_replace("#", "#", $row["email_address"]) . ') ' . $mail->ErrorInfo . '<br />';
}
$mail->clearAddresses(); // Clear all addresses for next loop
$mail->clearAttachments(); // Clear all attachments for next loop
}
}
}
}
if($mail_error_text != ""){
echo "<b>Email not sent to:</b><br>".$mail_error_text;
}
} else {
echo "Job Listing Insertion Fails";
}
} else {
echo "access denied";
}?>

php code : email not send

my problem is i have a code to send email to users when click in some button its works for me in localhost but not working when i push it in heroku server
<?php
if (isset($_POST['submitcmt']) && $_POST['token'] == $dcs_user_info['token']) {
//get rows in watchlist table if contest_id (job_id)==contest_id in database $watchlist_table = mysqli_query($conn, "SELECT * FROM watchlist WHERE contest_id='$contest_id'") or die("Error: " . mysqli_error($watchlist_table));
}
if (mysqli_num_rows($watchlist_table) > 0) {
//get rows from content table
$contentsTable = mysqli_query($conn, "SELECT * FROM contests WHERE id='$contest_id'")
or die("Error: " . mysqli_error($conn));
//to can use the rows in users table
$row_contents = mysqli_fetch_array($contentsTable, MYSQLI_ASSOC);
//get rows from users table
$userTable = mysqli_query($conn, "SELECT * FROM users WHERE id!='" . $dcs_user->user['id'] . "'")
or die("Error: " . mysqli_error($conn));
require 'vendor/vendor/phpmailer/phpmailer/PHPMailerAutoload.php';
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->SMTPAuth = true;
//$mail->SMTPDebug=2;
//$mail->Debugoutput = 'html';
$mail->SMTPOptions =
[
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
],
];
$mail->Host = 'smtp.gmail.com';
$mail->Username = 'faresalkhwaja#gmail.com';
$mail->Password = 'elkhawajah1';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
//to select all the email in database
while ($row_user = mysqli_fetch_array($userTable, MYSQLI_ASSOC)) {
$mail->From = 'tasqat';
$mail->FromName = 'tasqat';
$mail->addReplyTo('faresalkhwaja#gmail.com', 'tasqat');
$mail->addAddress($row_user['email'], $row_user['email']);
$mail->Subject = "new comment";
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$mail->Body = "job title :" . $row_contents['title'] . "<br>" . "user name :" . $row_comment['display_name'] . "<br>" . "date : " . $row_comment['date'] . "<br>" . "comment : " . $row_comment['comment'] . "<br>" . "host : " . $actual_link;
$mail->AltBody = 'this is body';
}
}//end while loop
Your hosting provider likely has disabled emailing to prevent its system being used for spamming. You should contact them to see if they will enable it for you.
If they will not, you may want to consider using a third-party service.

Customize Body of SMTP Mail Script

I have a basic smtp mail script that works great but the only thing that i need is to customize body of mail. I tried to define and insert values into the script but somewhere the code gives me error. Where I'm doing wrong?
<?
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "mail.host.com"; // SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "info#host.com"; // SMTP username
$mail->Password = "123456"; // SMTP password
$mail->From = "info#host.com";
$mail->Fromname = "John Doe";
$mail->AddAddress("info#gmail.com","John Doe");
$mail->Subject = $_POST['content'];
$mail->Body = (".$arrival_date.", ".$arrival_pickup_location.", ".$arrival_dropoff_location.", ".$arrival_flight_number.", ".$arrival_fligth_time.", ".$arrival_dropoff_adress.", ".$phone_number.", ".$reservation_name.", ".$email_adress.", ".$country.", ".$additional_requests.");
$arrival_date = $_POST['arrival_date'];
$arrival_pickup_location = $_POST['arrival_pickup_location'];
$arrival_dropoff_location = $_POST['arrival_dropoff_location'];
$arrival_flight_number = $_POST['arrival_flight_number'];
$arrival_fligth_time = $_POST['arrival_fligth_time'];
$arrival_dropoff_adress = $_POST['arrival_dropoff_adress'];
$reservation_name = $_POST['reservation_name'];
$phone_number = $_POST['phone_number'];
$email_adress = $_POST['email_adress'];
$passenger = $_POST['passenger'];
$country = $_POST['country'];
$additional_requests = $_POST['additional_requests'];
if(!$mail->Send())
{
echo "Mesagge not delivered <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message sent";
?>
You're setting the variables after you're trying to set the $mail->Body object with them.
Try:
<?php
$arrival_date = $_POST['arrival_date'];
$arrival_pickup_location = $_POST['arrival_pickup_location'];
$arrival_dropoff_location = $_POST['arrival_dropoff_location'];
$arrival_flight_number = $_POST['arrival_flight_number'];
$arrival_fligth_time = $_POST['arrival_fligth_time'];
$arrival_dropoff_adress = $_POST['arrival_dropoff_adress'];
$reservation_name = $_POST['reservation_name'];
$phone_number = $_POST['phone_number'];
$email_adress = $_POST['email_adress'];
$passenger = $_POST['passenger'];
$country = $_POST['country'];
$additional_requests = $_POST['additional_requests'];
$message = '<ul><li>' . $arrival_date . "</li>";
$message .= '<li>' . $arrival_pickup_location . "</li>";
$message .= '<li>' . $arrival_dropoff_location . "</li>";
$message .= '<li>' . $arrival_flight_number . "</li>";
$message .= '<li>' . $arrival_fligth_time . "</li>";
$message .= '<li>' . $arrival_dropoff_adress . "</li>";
$message .= '<li>' . $phone_number . "</li>";
$message .= '<li>' . $reservation_name . "</li>";
$message .= '<li>' . $email_adress . "</li>";
$message .= '<li>' . $country . "</li>";
$message .= '<li>' . $additional_requests . "</li></ul>";
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "mail.host.com"; // SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "info#host.com"; // SMTP username
$mail->Password = "123456"; // SMTP password
$mail->IsHTML(true);
$mail->From = "info#host.com";
$mail->Fromname = "John Doe";
$mail->AddAddress("info#gmail.com","John Doe");
$mail->Subject = $_POST['content'];
$mail->Body = $message;
if(!$mail->Send())
{
echo "Mesagge not delivered <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message sent";
?>
Also, I don't think that using $mail->AddAddress = ("info#gmail.com","John Doe"); would work, not sure ...
.. perhaps it does though! The way above in my answer definitely should work though xD!
What's the error that you're getting? Where did it start producing the error?
$mail->AddAddress("info#gmail.com","John Doe") doesn't have an "=" sign.
so it should read:
$mail->AddAddress = ("info#gmail.com","John Doe");
also, you can add html to the body so it reads a little nicer:
$mail->Body = "<html><body>";
$mail->Body .= "<table><tbody>";
$mail->Body .= "<tr><td>".$arrival_date."</td></tr>";
$mail->Body .= "</tbody></table>";
$mail->Body .= "</body></html>";

Categories