php code : email not send - php

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.

Related

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

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

send email on localhost with PHP

I want to send an email on localhost but don't really know how to do it.
I tried some different ways but it doesn't work.
I used PHPMailer https://github.com/PHPMailer/PHPMailer/tree/5.2-stable as the mailserver but I think thats maybe wrong implemented or so.
Don't know if it's important but I use MAMP.
This is what I currently have:
<?php
if (isset($_POST['submit'])) {
require("PHPMailer/PHPMailerAutoload.php");
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->SMTPSecure = "ssl";
$mail->SMTPAuth = true;
$mail->Username = "mail account";
$mail->Password = "password for account";
$mail->Port = "465";
$mail->setFrom('receiver mail', 'TEST');
$mail->addReplyTo('receiver mail', 'TEST');
$mail->addAddress('recipient mail');
$mail->Port = "465";
$mail->isHTML(true);
$mail->Subject = "test";
// get text from input fields
$email = $_POST['email'];
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$number = $_POST['number'];
$textarea = $_POST['textarea'];
$bodyContent =
"<p>Name: " . $name . "</p>
<p>E-Mail: " . $email . "</p>
<p>Telefonnummer: " . $number . "</p>
<p>Adresse: " . $address . $city . "</p>
<p>Anliegen: " . $textarea . "</p>";
$mail->Body = $bodyContent;
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
}
?>
Comment out the following two lines :
// ini_set("SMTP","ssl://smtp.gmail.com");
// ini_set("smtp_port","465");
And add the following under the line with $mail = new PHPMailer();
$mail->isSMTP();
And it will work, I have tried it on my laptop on XAMPP.
Okay, i finally found the solution. I updated my code to this
<?php
if (isset($_POST['sendButton'])) {
require("PHPMailer/PHPMailerAutoload.php");
require 'PHPMailer/class.phpmailer.php';
$mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "secret";
$mail->Password = "secret";
$subject = utf8_decode('test');
$mail->setFrom('secret', $subject);
$mail->addReplyTo('secret', $subject);
$mail->addAddress('secret');
$mail->Subject = utf8_decode('test');
$mail->Port = "587";
$mail->isHTML(true);
$email = $_POST['email'];
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$number = $_POST['number'];
$sendText = $_POST['sendText'];
$bodyContent =
"<p>Name: " . $name . "</p>
<p>E-Mail: " . $email . "</p>
<p>Telefonnummer: " . $number . "</p>
<p>Adresse: " . $address . ' ' . $city . "</p>
<p>Anliegen: " . $sendText . "</p>";
$mail->Body = $bodyContent;
}
?>
Besides I had to go to myaccount.google.com -> "Sign-in & security" -> "Apps with account access", and turn "Allow less secure apps" to "ON"
Now everything is fine.
Thank you for your help guys

Phpmailer not working on webserver

I am trying to get phpmailer to work on a web server. It does work with no problem on my xampp server but as soon as I put it on the web server it cant find these and it gives me the error. I also tried putting it on another web server and that doesn't work. I also copied the files from my xampp server to the web server and it still doesn't work.
use PHPMailer\PHPMailer\PHPMailer; (line 3)
use PHPMailer\PHPMailer\Exception; (line 4)
Error: parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or '('email.php on line 3
the code that the error points to is
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
function sendemail(){
require '../mail/src/PHPMailer.php';
require '../mail/src/SMTP.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
include "removed(was database)";
$name = $_POST['name'];
$Uemail = $_POST['email'];
$select = $_POST['select'];
$issue = $_POST['issue'];
$resolution = $_POST['resolution'];
$datesubmited = date("Y-m-d H:i:s");
//Server settings
$mail->SMTPDebug = 4; //1-4 // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'removed'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'removed'; // SMTP username
$mail->Password = 'removed'; // SMTP password
$mail->SMTPSecure = ''; // Enable TLS encryption, `ssl` also accepted
$mail->Port = removed; // TCP port to connect to
//Recipients
$email = 'removed'; //put in default email that corresponds with the username / passwoard.
$mail->setFrom( $email, 'removed');
$mail->addAddress($Uemail, $name);
$mail->addAddress('removed', 'removed');
$mail->addAddress('removed', 'removed'); // Add a recipient
// $mail->addAddress('', $name);
//Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Request from ' . $name;
$mail->Body = 'Details ' . "<br>" .
"Date: " . $datesubmited . "<br>" .
"Name: " . $name . "<br>" .
"Email Address: " . $email . "<br>" .
"Area of Concern: " . $select . "<br>" .
"Issue: " . $issue . "<br>" .
"Suggested Resolution: " . $resolution . "<br>";
$mail->AltBody = 'Hello '. $name . ' your request has been sumbited!'.'</b>';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->send();
echo "Thank you " . $name . " for your submission." . "<br>" . "Someone will repsond to you shortly.";
echo "<br>";
echo "Go back home " . "removed" ;
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
}
?>
At first glance I would say that the use function seems to call the problem. Could you try adding these lines before your first use call and check the result:
$funcDefinition = new ReflectionFunction('use');
print $funcDefinition->getFileName() . ', ' .
$funcDefinition->getStartLine();
Check the results of the call on your local and your remote systems and compare the outcome. I don't think that you are deploying on Pre-PHP-5.3 systems where the use command was not available but please also add some information regarding the different PHP versions used locally and remote.
In fact it seems that you get your error message in case you are deploying on PHP 5.2 systems as this SO thread mentions. So first check has to be the PHP version (i.e. by adding a phpinfo(); before your first use call).
Conclusion: question author received the error due to deploying on a PHP 5.2 system without use support.

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";
}?>

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