How to get PHP variable from another file? - php

I'm trying to make a forgot password system with PHPMailer on xampp.
But when I send an email,the email body is a html mail template,what I get from another file $mail->Body = file_get_contents('mail_template.php');,and I have problem,because I don't know how should I get the data of the $url variable and send it to mail_template.php file to use it for the link in the mail.
I tried the include 'filename.php'; command,but haven't worked.
Here is the code:
if (isset($_POST["submitButton"])) {
$emailTo = $_POST["email"];
$code = md5(uniqid(rand(), true));
$query = $con->prepare("INSERT INTO resetpasswords(code,email) VALUES('$code', '$emailTo')");
$query->execute();
if (!$query) {
exit("Something went wrong...");
}
$mail = new PHPMailer(true);
try {
//Server settings // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mail#gmail.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 465; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('mail#mail.com', 'Email');
$mail->addAddress($emailTo); // Add a recipient
$mail->addReplyTo('no-reply#website.com', 'No reply');
// Content
$url = "http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/resetPassword/code/$code";
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Reset your password!';
$mail->Body = file_get_contents('mail_template.php');
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
} catch (Exception $e) {
echo "Message could not be sent. Error: {$mail->ErrorInfo}";
}
header("refresh:10;url=login.php");
}
So from this php file,I want to send the data of the $url to the mail_template.php
Is this possible to do?

To send data to another url in php you have to try the following url:
`mail_template.php?data=mail#gmail.com`
then inside an empty mail_template.php do -
<?php
if (isset($_GET['data'])) {
$test = $_GET['data'];
//print the data added to the url
echo $test;
}
?>

Related

php auto mailer addAddress

I want to send otp mail to user by fetching email value from database . I am using php auto mailer . It works when i use mail address directly but when i retrieve it from database i cant send it . Can anyone please help me with sending it .
function mailit()
{
$rand=rand(100000,999999);
$user=$_SESSION['user'];
$sql=mysqli_query($db,"UPDATE `doctor_login` SET `otp`='$rand' WHERE `doctor_id`='1'");
$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 = 'myusername '; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587 ; // TCP port to connect to
$mail->setFrom('dont_reply_back#example.xyz');
$mail->addAddress('$row'); // Add a recipient
$mail->addReplyTo('dont_reply_back#example.xyz');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'THis is your OTP';
$mail->Body = 'Your otp is '.$rand;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
}
Code for retrieving and displaying of email
$mailadd=mysqli_query($db,"SELECT `doctor_email` FROM `doctor_login` WHERE `doctor_id`='1'");
$row = mysqli_fetch_array($mailadd,MYSQLI_ASSOC);
echo $row['doctor_email'];
$row2=$rowa['doctor_email'];
echo $row2;
i have used both $row and $row2 in $mail->addAddress but doesnt seem to work . What changes can i do . it works whwn i give a specific address
I think this is a scope issue. If you are calling this code in the main body of the code
$mailadd=mysqli_query($db,"SELECT `doctor_email`
FROM `doctor_login`
WHERE `doctor_id`='1'");
$row = mysqli_fetch_array($mailadd,MYSQLI_ASSOC);
Then I assume you call mailit() after this, so pass the data you want to use as a parameter to the mailit() function so it is available inside the function scope.
function mailit($row)
{
$rand=rand(100000,999999);
$user=$_SESSION['user'];
$sql=mysqli_query($db,"UPDATE `doctor_login` SET `otp`='$rand' WHERE `doctor_id`='1'");
$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 = 'myusername '; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587 ; // TCP port to connect to
$mail->setFrom('dont_reply_back#example.xyz');
$mail->addAddress($row['doctor_email']); // Add a recipient
$mail->addReplyTo('dont_reply_back#example.xyz');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'THis is your OTP';
$mail->Body = 'Your otp is '.$rand;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
}
$mailadd=mysqli_query($db,"SELECT `doctor_email`
FROM `doctor_login`
WHERE `doctor_id`='1'");
$row = mysqli_fetch_array($mailadd,MYSQLI_ASSOC);
mailit($row);
You should have been getting errors from your original code so in future add the following:
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
// if you are using the `mysqli` API
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
to the top of your script. This will force any mysqli_ errors to generate an Exception that you can see on the browser as well as normal PHP errors.

PHPmailer how to show message

How I can show success message after to click send in my form? my phpmailer is working but I want to also after to click send to redirect to my homepage (index.html) and show my message div. This is my php code.
<?php
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$subject = $_POST['subject'];
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.xxxxxxx.pl'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxxx#xxxxxxxx.pl'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom($email, $name);
$mail->addAddress('xxxx#gmail.com', 'xxxxxxxx'); // Add a recipient // Name is optional
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = 'Body test';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
header('Location: index.html');
}
And this is my Jquery code to show/hidden div succes:
$('.box-up').animate({top : 150}, 'normal').delay(3000).animate({top : -500}, 'normal');
You could send extra parameter with your request :
header('Location: index.php?r=1');
Then in your index page get the parameter and use it to show the box :
<script>
var result="<?php echo $_GET['r']; ?>";
if(parseInt(result)){
$('.box-up').animate({top : 150}, 'normal').delay(3000).animate({top : -500}, 'normal');
}
</script>
Hope this helps.

SMTP Error: Could not authenticate. Message could not be sent. Mailer Error: SMTP Error: Could not authenticate

When I trying to send a email using PHP SMTP email server, following error has occurred.
SMTP Error: Could not authenticate. Message could not be sent.
Mailer Error: SMTP Error: Could not authenticate.
Following is my code that I have used.
function supervisorMail(){
global $error;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = "***#gmail.com";
$mail->Password = "****";
$mail->SetFrom("***#gmail.com", "Employee Leave Management System");
$userID=$_SESSION['userID'];
$select_query = mysql_query("SELECT * FROM employee WHERE emp_id = '$userID'");
$select_sql = mysql_fetch_array($select_query);
$name=$select_sql['manager_name'];
var_dump($name);
$select_query1 = mysql_query("SELECT email FROM employee WHERE emp_id='$name'");
$select_sql1 = mysql_fetch_array($select_query1);
$email=$select_sql1['email'];
var_dump($email);
$mail->Subject = "subject ";
$mail->Body = "something.";
$mail_to = $email;
$mail->AddAddress($mail_to);
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
}
How can I fixed this error.
The error message is very clear "Could not authenticate".
I would say you are correctly using the PHPMailer class, but just not filling in the correct gmail account details.
I suppose that in your question the fields username and password look like
$mail->Username = "#gmail.com";
$mail->Password = "";
just because you, obviously, don't want to share them, I would suggest to present them like this in the question
$mail->Username = "********#gmail.com";
$mail->Password = "********";
So if you are using the correct username and password there are other two things to check
Maybe your setting "Access for less secure apps" is turned off.
After you login from the web you can turn it on from this page
https://www.google.com/settings/u/0/security/lesssecureapps
If that is On, it might be possible you have 2-Step Verification enabled in your gmail account. If this is the case, you need to create an App specific password.
Follow this link for a step by step guide on how to do it
http://email.about.com/od/gmailtips/fl/How-to-Get-a-Password-to-Access-Gmail-By-POP-or-IMAP.htm
Please unable your less secure app
and then
Try to comment this line
//$mail->IsSMTP();
I hope it will work!
You may try to use google app password for authentication:
https://support.google.com/accounts/answer/185833?hl=en
2-Step-Verification & 2. App Passwords
As mentioned in comment, you need to enter valid gmail id and password.
Please refer below demo code.
<?php
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '*****001#gmail.com'; // SMTP username
$mail->Password = 'ma****02'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->setFrom('ravi******#gmail.com', 'Mailer'); // Add set from id
$mail->addAddress('er.ravihirani#gmail.com', 'Ravi Hirani'); // 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 = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
I ran into this error message and wanted to post an answer in case it can help someone else. I have phpmailer installed with composer and am running php 7. The implementation of the phpmailer script that threw the error is in a php object method. The password variable, set in a config file elsewhere, needed to be declared as a global in the object context otherwise it did not contain the actual password and thus caused the authentication error..
global $password; // <- this added to make script work
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
// Set mailer to use SMTP
$mail->Host = '*******.com';
$mail->SMTPAuth = true;
$mail->Username = 'no-reply#*******.com';
$mail->Password = $password;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('no-reply#*******.com', '******* - DO NOT REPLY');
//$mail->isHTML(true);
$mail->AddAddress($user->email);
$mail->Subject = "*******";
$mail->Body = "*******";
$mail->send();
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
In my case it was because I didn't turn on the Less secure app access from here: https://myaccount.google.com/lesssecureapps

Sending mail with PHPMailer

Im trying to send bulk of emails containing passwords to the students taking an exam in a particular subject.Now, Im having an error "SMTP Error: Could not connect to SMTP host. Mailer Error () SMTP Error: Could not connect to SMTP host." What could possibly be the problem?
my code as follows:
<?php
//error_reporting(E_ALL);
error_reporting(E_STRICT);
//date_default_timezone_set('America/Toronto');
require_once('PHPMailer-phpmailer-5.2.0/class.phpmailer.php');
include("PHPMailer-phpmailer-5.2.0/class.smtp.php"); //optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "localhost";
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent
$mail->Host = "mail.yahoo.com"; // sets the SMTP server*/
$mail->Port = 26;
$mail->Username = "***********#yahoo.com"; // SMTP account username
$mail->Password = "****************"; // SMTP account password
$mail->From = "*************#yahoo.com";
$mail->FromName = "Exam System";
//$mail->IsHTML(true);
while ($row_email = mysql_fetch_array ($email)) {
$mail->Subject = "Subject: ".$row_email['subject_description']."";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->Body = "This is your password for ".$row_email['exam_title']." : ".$row_email['pass_password']."";
$mail->AddAddress($row_email['stud_email']);
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row_email['stud_email']) . ') ' . $mail->ErrorInfo . '<br />';
} else {
echo "Message sent to :" . $row_email['stud_email'] . ' (' . str_replace("#", "#", $row_email['stud_email']) . ')<br />';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
}
mysql_free_result($email);
?>
Try this...
add this code for Set secutiry
// if you're using SSL
$mail->SMTPSecure = 'ssl';
// OR use TLS
$mail->SMTPSecure = 'tls';
Try with gmail, as i am not aware of Yahoo's SMTP server. [Also, use the gmail credentials (username, password)]
$mail->Host = "smtp.gmail.com";
function SendMailWithGmailSMTP($author, $email, $text)
{
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "localhost"; // Sets the SMTP hosts
$mail->Port = 587; // Sets the default SMTP server port.
$mail->SMTPAuth = false; // Sets SMTP authentication. Utilizes the Username and Password variables.
$mail->Username = "...#gmail.com";
$mail->Password = "...";
$mail->From = $email;
$mail->FromName = $author;
$mail->CharSet = "ISO-8859-9";
$mail->AddAddress("...#gmail.com");
$mail->Subject = "Hi. This is a Subject!";
$mail->IsHTML(true);
$mail->Body = $text;
if($mail->Send()) return true; else echo '<script language="javascript">alert("'.$mail->ErrorInfo.'");</script>';
}
Write this function for send mail and call this function like this:
SendMailWithGmailSMTP("Aziz Yılmaz", "...#gmail.com", "Bla bla bla")

PHPMAILER Not sending and not giving error

I am trying to let users fill out a contact form, which will then be sent to my email. But its not working for some reason. I just get a blank page with no error message or any text and email is also not sent.
if (isset($_POST['submit']))
{
include_once('class.phpmailer.php');
$name = strip_tags($_POST['full_name']);
$email = strip_tags ($_POST['email']);
$msg = strip_tags ($_POST['description']);
$subject = "Contact Form from DigitDevs Website";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
//$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "info#example.com"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress('info#example.com', 'Information');
$mail->AddReplyTo($email, 'Wale');
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $msg;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
You need to call:
$mail = new PHPMailer(true); // with true in the parenthesis
From the documentation:
The true param means it will throw exceptions on errors, which we need
to catch.
Its working now, i didnt include the 'class.smtp.php' file. The working code is below:
if (isset($_POST['submit']))
{
include_once('class.phpmailer.php');
require_once('class.smtp.php');
$name = strip_tags($_POST['full_name']);
$email = strip_tags ($_POST['email']);
$msg = strip_tags ($_POST['description']);
$subject = "Contact Form from DigitDevs Website";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
//$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "info#example.com"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress('info#example.com', 'Information');
$mail->AddReplyTo($email, 'Wale');
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $msg;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
I had the same problem with no error message even with SMTPDebug enabled. After searching around for working examples I noticed that I didn't include the SMTP Secure value. Try adding this line:
$mail->SMTPSecure = 'ssl'; //secure transfer enabled
Work like a charm now.
I had a similar problem. In reference to #Syclone's answer. I was using the default "tls".
$mail->SMTPSecure = 'tls';
After I changed it to
$mail->SMTPSecure = 'ssl';
It worked ! My mailserver was only accepting connections over SSL.
What worked for me was setting From as Username and FromName as $_POST['email']
Hope this helps
PHPMailer use exception.
Try this
try {
include_once('class.phpmailer.php');
$name = strip_tags($_POST['full_name']);
$email = strip_tags ($_POST['email']);
$msg = strip_tags ($_POST['description']);
$subject = "Contact Form from DigitDevs Website";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
//$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "info#example.com"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress('info#example.com', 'Information');
$mail->AddReplyTo($email, 'Wale');
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $msg;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->Send();
exit;
} catch (phpmailerException $e) {
echo $e->errorMessage(); //error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage();
}
I was trying to load an HTML file to send, which did not belong to the www-data group on my Ubuntu server.
chown -R www-data *
chgrp -R www-data *
Problem solved!
I was debating whether to write my own handler or crow-bar PHPMailer into my existing class structure. In the event it was very easy because of the versatility of the spl_autoload_register function which is used within the PHPMailer system as well as my existing class structure.
I simply created a basic class Email in my existing class structure as follows
<?php
/**
* Provides link to PHPMailer
*
* #author Mike Bruce
*/
class Email {
public $_mailer; // Define additional class variables as required by your application
public function __construct()
{
require_once "PHPMail/PHPMailerAutoload.php" ;
$this->_mailer = new PHPMailer() ;
$this->_mailer->isHTML(true);
return $this;
}
}
?>
From a calling Object class the code would be:
$email = new Email;
$email->_mailer->functionCalls();
// continue with more function calls as required
Works a treat and has saved me re-inventing the wheel.
Try this ssl settings:
$mail->SMTPSecure = 'tls'; //tls or ssl
$mail->SMTPOptions = array('ssl' => array('verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true));

Categories