skip to Main Content

I am using PHPMailer to send emails with verification code. When I tried putting it inside a function and try to submit the form , the email is not being sent .

I have used the valid gmail ID for username , password and setFrom mail address.

$mail->Username   = '[email protected]';                
$mail->Password   = 'secret'; 
$mail->setFrom('[email protected]', 'Test Email') 

but still the email is not being sent.

Is there something wrong in the code? Please if any one can help me with this.

<?php  

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;

//Load Composer's autoloader
require 'vendor/autoload.php';

function sendmail($email,$v_code) {
  //Create an instance; passing `true` enables exceptions
  $mail = new PHPMailer(true);

  try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //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   = '[email protected]';                     //SMTP username
    $mail->Password   = 'secret';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    //Recipients
    $mail->setFrom('[email protected]', 'Test Email');
    $mail->addAddress($email);     //Add a recipient
   
    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = 'Email verification code';
    $mail->Body    =  "click the link to verify<a href=''>click here</a>";
        
    $mail->send();
    return true;
  }
  catch (Exception $e) {
    return false;
  }
}

if(isset($_POST['signup-submit'])) {
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password = $_POST['password'];
  $cnfmpwd = $_POST['repeatpsw'];
    
  if (empty($username)) {  
    header("Location: ../signup.php?error=requiredusername");
    exit();
  }
  else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
    header("Location: ../signup.php?error=invaliedusernameemail");
    exit();
  }
  else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header("Location: ../signup.php?error=invaliedemail");
    exit();
  }
  else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
    header("Location: ../signup.php?error=invalidusername");
    exit();
  }
  else if (empty($email)){
    header("Location: ../signup.php?error=requiredemail");
    exit();
  }
  else if (empty($password)){
    header("Location: ../signup.php?error=requiredpassword");
    exit();
  }
  else if (empty($cnfmpwd)){
    header("Location: ../signup.php?error=requiredcnfmpwd");
    exit();
  }
  else if ($password !== $cnfmpwd) {
    header("Location: ../signup.php?error=pwddonotmatch");
    exit();
  }
  else {
    $check_user="SELECT * FROM users WHERE username ='$_POST' OR email = '$_POST[email]'";
    $result=mysqli_query($conn,$check_user);
    
    if($result) {
      if(mysqli_num_rows($result)>0)
      {
        $result_fetch = mysqli_fetch_assoc($result);
        if($result_fetch['username']==$_POST['username']) {
          header("Location: ../signup.php?error=usernameexists");
          exit();
        }
        else {
          header("Location: ../signup.php?error=emailexists");
          exit();
        }
      }
      else {
        $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
        $v_code = bin2hex(random_bytes(16));
        $query = "INSERT INTO `users`(`username`, `email`, `password`, `verification_code`, `v_user`) VALUES ('$username','$email','$password','$v_code','0')";
    
        if(mysqli_query($conn,$query) && sendmail($email,$v_code) ) { // data inserted successfully
          header("Location: ../signup_success.php?signup=success");
          exit();
        }
        else { // if data cannot be inserted
          header("Location: ../signup.php?unsuccesss=unsuccesss");
          exit();
        }
      }
    }
  }
  mysqli_close($conn);  
}
else {
  header("Location: ../signup.php");
  exit();
} 
?>

2

Answers


  1. Your code looks mostly correct at a glance, but I can point out a couple of potential issues and improvements:

    1. Missing Connection to the Database: It seems that your code interacts with a database using SQL queries (mysqli_query). However, I don’t see the part of your code where you establish a connection to the database using mysqli_connect before executing queries. Make sure you establish a database connection before querying the database.

    2. SMTP Secure Option: Gmail generally uses STARTTLS encryption on port 587. However, in your code, you have used ENCRYPTION_SMTPS which corresponds to port 465 and SSL/TLS encryption. Make sure you are using the correct combination of encryption and port for your SMTP configuration.

    3. Debugging: If the email is not being sent, consider enabling debugging for PHPMailer using $mail->SMTPDebug to get more insights into the issue.

    Login or Signup to reply.
  2. You need to enable 2 factor authentication in your settings (same place you used to see the less secure apps) then once you enable that you will see a new option called App Passwords – you can then create a app password that you would use for the SMTP settings

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search