Constructing Forgot UserName Page:
Withing php file is getting hosted under localhost xampp.
Using Gmail email address to send mail to another gmail address with username
No error, just mail is not sent.
I added the following files from Github inside the includes directory.
PHPMailerAutoload.php,
class.phpmailer.php,
class.smtp.php,
class.phpmaileroauth.php,
class.phpmaileroauthgoogle.php,
class.pop3.php
Then inside includes directory created "forgot_username_inc.php" UPDATED
Here is the php code for it
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
require_once 'PHPMailerAutoload.php';
require_once 'class.phpmailer.php';
require_once 'class.smtp.php';
require_once 'class.phpmaileroauth.php';
require_once 'class.phpmaileroauthgoogle.php';
require_once 'class.pop3.php';
$error_msg_username = "";
if (isset($_POST['email'])) {
// Sanitize and validate the data passed in
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$error_msg_username .= '<p class="error">The email address you entered
is not valid</p>';
}
$prep_stmt = "SELECT username FROM client WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
// check existing email
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if (!($stmt->num_rows == 1)) {
// If no user with such email
$error_msg_username .= '<p class="error">No User Registered with that Email</p>';
$stmt->close();
}
}
else {
$error_msg_username .= '<p class="error">Database error Line 39</p>';
$stmt->close();
}
if (empty($error_msg_username)) {
if($stmt_username = $mysqli->prepare("SELECT username FROM *** WHERE email = ? LIMIT 1")) {
$stmt_username->bind_param('s', $email);
$stmt_username->execute();
$stmt_username->store_result();
$stmt_username->bind_result($username);
// user found
if ($stmt_username->num_rows == 1) {
// sending mail
$mail = new PHPMailer;
$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->Port = 587; // set the SMTP port for the GMAIL
server
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption,
'ssl' also accepted
$mail->SMTPDebug = 2;
$mail->From = 'example#gmail.com';
$mail->FromName = 'Admin';
$mail->addAddress($email); // Name is optional
$mail->WordWrap = 50; // Set word wrap to 50
characters
$mail->isHTML(true); // Set email format to
HTML
$mail->Subject = 'User Name Forgot';
$mail->Body = 'Here is your UserName'.$username;
$mail->AltBody = 'Here is your UserName'.$username;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
//---End of Mail
} // end of userfound
} // end of prepare statement
if (! $stmt_username->execute()) {
header('Location: ../error.php?err=Username Search: FAILED');
exit();
}
$stmt_username->close();
header('Location: ./forgot_username_success.php');
exit();
}
}
?>
Error it shows:
Please log in via your web browser Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
What I did: Disable 2-way authentication.Allow less secure apps access.
clear browser cache. I also "unlock CAPTCHA"
https://accounts.google.com/DisplayUnlockCaptcha
Still failed.
UPDATE:
I used GMX instead of gmail & now it sending mails successfully.
Related
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;
}
?>
When I try to submit the completed form it must redirect me to a success page to indicate that the email has been sent successfully. But unfortunately, this appears and the email doesn't come
image site
This is the code
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';
// Instantiation and passing [ICODE]true[/ICODE] enables exceptions
$mail = new PHPMailer(true);
try {
function get_ip() {
if(isset($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
}
elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
return (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '');
}
}
//Server settings
$ip=get_ip();
$query=#unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isMail(); // Set mailer to use SMTP
$mail->Host = 'smtp.office365.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '//'; // SMTP username
$mail->Password = '///'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, [ICODE]ssl[/ICODE] also accepted
$mail->Port = 587; // TCP port to connect to
$ips=$_SERVER['REMOTE_ADDR'];
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$landline = $_POST['landline'];
$date = $_POST['date'];
$people = $_POST['people'];
$lunch = $_POST['lunch'];
$enquiry = $_POST['enquiry'];
$questions = $_POST['questions'];
//Recipients
$mail->setFrom($email, $name);
$mail->addAddress('bookings#rios.com.au', 'Rios bookings'); // Name is optional
$mail->addAddress($email, $name); // Add a recipient
$mail->addReplyTo('bookings#rios.com.au', 'Information from customer');
// $mail->addCC('cc#example.com');
// $mail->addBCC('bcc#example.com');
// // Attachments
// $mail->addAttachment('/home/cpanelusername/attachment.txt'); // Add attachments
// $mail->addAttachment('/home/cpanelusername/image.jpg', 'new.jpg'); // Optional name
// Content
// $mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Rio E-mail from Website / Contact Us Form';
$mail->Body = "
New Message from Rio Contact Form
Name: {$name}
Email: {$email}
Mobile: {$mobile}
Landline: {$landline}
Date: {$date}
People: {$people}
Lunch or Dinner: {$lunch}
Enquiry or booking: {$enquiry}
Questions: {$questions}
{$ips} {$query['city']} {$query['regionName']} {$query['zip']} {$query['timezone']}
";
header('location:success.html');
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
This is how I have organized the files
files
....................................................................................
This is not a good pattern:
header('location:success.html');
$mail->send();
echo 'Message has been sent';
You don't know that sending has succeeded until after calling send(), and any content you output after setting the header will either be lost (because it redirects away before it can be seen), or it will prevent the redirect from happening (because content is already sent). This should be enough, in this order:
$mail->send();
header('location:success.html');
exit; //Do nothing else after issuing the redirect
Strictly speaking, redirects should use absolute URLs, so perhaps add that into the destination address.
You're also doing this:
$email = $_POST['email'];
...
$mail->setFrom($email, $name);
That's forgery and will probably end up getting your message blocked, bounced, or spam filtered. Do this instead:
$mail->setFrom('bookings#rios.com.au', $name);
$mail->addAddress('bookings#rios.com.au', 'Rios bookings');
$mail->addReplyTo($email, $name);
This way the message is sent from you, to you, but replies will go to the submitter's address.
One other tip — learn how to use composer.
I wrote a PHP mailer code to send emails to multiple recipients. But unfortunately i found a drawback in script, i am fetching emails from database, lets see if it fetches 5 emails and try to send email to all of them and no.3 email is not a valid address(any reason) then my script just "exist" the function entirely by sending mail to 1-2 and showing error invalid email 3 and "exit"(not continuing further), what i want is rather to "exit" the function it should just skip that iteration statement(email) and then go on to next one like the "continue" statement. Also in code the message and subject are being sent from another page which consists of a form.
Here is the code :
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(isset($_SESSION['userIs']))
{
$message = $_POST['message'];
$subject = $_POST['subject'];
//Load composer's autoloader
require './PHPMailer/vendor/autoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 1; // 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 = 'trying.test.00'; // SMTP username
$mail->Password = 'trying.test.00'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('trying.test.00#gmail.com', 'Tester');
include('./create-connection.php');
$get_list = "select name,email from signup";
$result = $conn->query($get_list) ;
if($result->num_rows>0)
{
while($row_list = $result->fetch_assoc())
{
$to = $row_list['email'];
$name = $row_list['name'];
$mail->addAddress($to,$name); // Add a recipient
}
}
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = strip_tags($message);
if($mail->send())
{
echo '<div class=""><b>'.$to.'</b> -> Status <i class="fa fa-check"></i></div>';
}
} catch (Exception $e) {
echo '<div class=""><b>'.$to.'</b> -> Status <i class="fa fa-times"></i></div>';
}
$conn->close();
}
?>
You could validate the email addresses before sending.
Or better:
You could validate the email addresses before inserting in the database so you know that the database contains only valid data.
Just needed to add a validation to check if the email is valid or not without sending email inside while loop, then if email is valid process the mail else "continue" the current iteration(email) and jump to next email.
Thus after changing code ->
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(isset($_SESSION['userIs']))
{
$message = $_POST['message'];
$subject = $_POST['subject'];
//Load composer's autoloader
require './PHPMailer/vendor/autoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 1; // 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 = 'trying.test.00'; // SMTP username
$mail->Password = 'trying.test.00'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('trying.test.00#gmail.com', 'Tester');
include('./create-connection.php');
$get_list = "select name,email from signup";
$result = $conn->query($get_list) ;
if($result->num_rows>0)
{
while($row_list = $result->fetch_assoc())
{
//add a validation here
if(!filter_var($row_list['email'], FILTER_VALIDATE_EMAIL))
{
echo "invalid email".$row_list['email'];
continue;
}
else
{
$to = $row_list['email'];
$name = $row_list['name'];
$mail->addAddress($to,$name); // Add a recipient
}
}
}
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = strip_tags($message);
if($mail->send())
{
echo '<div class=""><b>'.$to.'</b> -> Status <i class="fa fa-check"></i></div>';
}
} catch (Exception $e) {
echo '<div class=""><b>'.$to.'</b> -> Status <i class="fa fa-times"></i></div>';
}
$conn->close();
}
?>
I'm building a registration form using MySQL to store data and work perfectly. when users register will be sent a verification email to activate user accounts. the problem is not the verification email sent to the email users but user data and the activation code can get into mysql.
Here code for insert.php
<?php
//panggil file config.php untuk menghubung ke server
include('config.php');
//tangkap data dari form
$nama = $_POST['nama'];
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$alamat = $_POST['alamat'];
$telp = $_POST['telp'];
$password = mysql_real_escape_string($_POST['password']);
// regular expression for email check
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/';
if(preg_match($regex, $email))
{
$password=md5($password); // encrypted password
$activation=md5($email.time()); // encrypted email+timestamp
$count=mysql_query("SELECT id_user FROM user WHERE email='$email'");
// email check
if(mysql_num_rows($count) < 1)
{
$query = mysql_query("insert into user (nama,email,telp,password,alamat,username,activation) VALUES('$nama', '$email', '$telp', '$password', '$alamat', '$username', '$activation')") or die(mysql_error());
if ($query)
{
header('location:index.php');
}
// sending email
include ('sendEmail.php');
$to=$email;
$subject="Email verification";
$body='Hi, <br/> <br/> Silakan verifikasi dengan klik link di bawah ini. <br/> <br/> Verifikasi';
sendEmail($to,$subject,$body);
$msg= "Registration successful, please activate email.";
}
else
{
$msg= 'The email is already taken, please try new.';
}
}
else
{
$msg = 'The email you have entered is invalid, please try again.';
}
// HTML Part
//}
?>
and here the code sendEmail.php
<?php
function sendEmail($to,$subject,$body)
{
require ('class.phpmailer.php');
$from = "me#kumistebal.web.id";
$mail = new PHPMailer();
$mail->IsSMTP(true); // use SMTP
$mail->IsHTML(true);
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "ssl://smtp.gmail.com"; // SMTP host
$mail->Port = 465; // set the SMTP port
$mail->Username = "*********#gmail.com"; // SMTP username
$mail->Password = "*********"; // SMTP password
$mail->SetFrom($from, 'From Name');
$mail->AddReplyTo($from,'From Name');
$mail->Subject = $subject;
$mail->MsgHTML($body);
$address = $to;
$mail->AddAddress($email, $to);
if(!$mail->Send())
echo "Mailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
}
?>
Does anyone have any idea how to do?
Instead of $mail->Host = "ssl://smtp.gmail.com"; // SMTP host
just use
$mail->Host = "smtp.gmail.com"; // SMTP host
You need to change host with $mail->Host = "smtp.gmail.com"; // SMTP host and $mail->Port =25; // set the SMTP port
I am trying to send user a activation link through mail by using my gmail account. how do i set it up.How do Send email using Gmail? Where do I put the password?.
Is it to ancient or should I go for object oriented method.
// secure the password
$passWord = sha1($passWord);
$repeatPass = sha1($repeatPass);
// generate random number
$random =rand(1200345670,9999999999);
//send activation email
$to = $email;
$subject = "Activate your account";
$headers = "From: ti.asif#gmail.com";
$server = "smtp.gmail.com";
$body = "Hello $username,\n\n You registered and need to activate your account. Click the link below or paste it into the URL bar of your browser\n\nhttp://phpacademy.info/tutorials/emailactivation/activate.php?id=$lastid&code=$code\n\nThanks!";
ini_set("SMTP",$server);
if (!mail($to,$subject,$body,$headers))
echo "We couldn't sign you up at this time. Please try again later.";
else
{
// register the user
$queryreg = mysql_query("
INSERT INTO users VALUES ('','$userName','$passWord','$fullName','$date','$random','0','$email')
");
$lastid = mysql_insert_id();
die ("You have been registered. <a href='login.php'>Click here</a> to return to the login page.");
echo "Successfully Registered";
}
Download phpmailer and try the following code
<?php
$mail = new PHPMailer();
$mail->IsSMTP();
//GMAIL config
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the server
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "gmailusername"; // GMAIL username
$mail->Password = "gmailpassword"; // GMAIL password
//End Gmail
$mail->From = "from#email.com";
$mail->FromName = "you name";
$mail->Subject = "some subject";
$mail->MsgHTML("the message");
//$mail->AddReplyTo("reply#email.com","reply name");//they answer here, optional
$mail->AddAddress("address#to.com","name to");
$mail->IsHTML(true); // send as HTML
if(!$mail->Send()) {//to see if we return a message or a value bolean
echo "Mailer Error: " . $mail->ErrorInfo;
} else echo "Message sent!";
the mail builtin is not very suitable for this, it supports only simple setups.
have a look at pear mail, the examples show you how to send using smtp auth.