Question
I am facing an issue with PHPMailer where it doesn’t seem to be sending emails. I’ve set up a simple registration system, and the verification email using PHPMailer is not reaching the intended recipients. I’ve included the relevant code below:
<?php
// Include PHPMailer autoloader
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
use PHPMailerPHPMailerPHPMailer;
// Include configuration
include 'config.php';
// Function to sanitize input
function sanitizeInput($input) {
return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}
// Function to send verification email
function sendmail($to, $subject, $verificationCode) {
$mail = new PHPMailer(true); // Set true for exceptions
try {
// Configure SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]'; // Use the full Gmail address here
$mail->Password = 'soafohendcfhclzn';
$mail->Port = 587; // Adjust the port if necessary
$mail->SMTPSecure = 'tls'; // Add this line
// Set email parameters
$mail->setFrom('[email protected]', 'APIForm');
$mail->addAddress($to);
$mail->Subject = $subject;
// Styled HTML body
$mail->isHTML(true);
$mail->Body = '
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333;
}
p {
color: #555;
}
.verification-code {
font-size: 24px;
font-weight: bold;
color: #3498db;
}
</style>
</head>
<body>
<div class="container">
<h1>Account Verification Code</h1>
<p>Dear user,</p>
<p>Your verification code is: <span class="verification-code">' . $verificationCode . '</span></p>
<p>Thank you for registering!</p>
</div>
</body>
</html>
';
// Send the email
$mail->send();
// Email sent successfully
return true;
} catch (Exception $e) {
// Email not sent
return false;
}
}
// Function to handle registration API
function register() {
global $pdo; // Make $pdo variable available in this function
$subject = "APIForm Account Verification";
// Assuming you receive registration data in the POST request
$firstname = isset($_POST['firstname']) ? sanitizeInput($_POST['firstname']) : null;
$lastname = isset($_POST['lastname']) ? sanitizeInput($_POST['lastname']) : null;
$email = isset($_POST['email']) ? sanitizeInput($_POST['email']) : null;
$password = isset($_POST['password']) ? sanitizeInput($_POST['password']) : null;
$confirmPassword = isset($_POST['confirm_password']) ? sanitizeInput($_POST['confirm_password']) : null;
// Check if all required fields are provided
if ($firstname && $lastname && $email && $password && $confirmPassword) {
// Check if passwords match
if ($password === $confirmPassword) {
// Check if the email already exists in the database
$stmtCheckEmail = $pdo->prepare('SELECT COUNT(*) FROM accounts WHERE email = ?');
$stmtCheckEmail->execute([$email]);
$emailExists = (bool)$stmtCheckEmail->fetchColumn();
if (!$emailExists) {
// Generate a unique user token using uniqid
$userToken = uniqid('user_', true);
// Generate a 6-digit code
$verificationCode = sprintf('%06d', mt_rand(0, 999999));
// Sending verification email
if (sendmail($email, $subject, $verificationCode)) {
// Hash the password for security
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
try {
// Insert data into the accounts table using a prepared statement
$stmt = $pdo->prepare('INSERT INTO accounts (userToken, firstname, lastname, email, password, creationDate, code) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?)');
$stmt->execute([$userToken, $firstname, $lastname, $email, $hashedPassword, $verificationCode]);
// Respond with a success message
$response = array('success' => true, 'message' => 'Registration successful', 'userToken' => $userToken);
} catch (PDOException $e) {
$response = array('success' => false, 'message' => 'Error inserting data into the database');
}
} else {
$response = array('success' => false, 'message' => 'Error sending verification email');
}
} else {
$response = array('success' => false, 'message' => 'Email already exists. Please use a different email address.');
}
} else {
$response = array('success' => false, 'message' => 'Passwords do not match');
}
} else {
$response = array('success' => false, 'message' => 'All fields are required');
}
// Send JSON response
header('Content-Type: application/json');
echo json_encode($response);
}
// Function to handle login API
function login() {
global $pdo; // Make $pdo variable available in this function
// Assuming you receive username and password in the POST request
$username = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
// Check if both username and password are provided
if ($username && $password) {
try {
// Fetch user information from the database based on the provided username (email)
$stmt = $pdo->prepare('SELECT id, userToken, firstname, lastname, email, creationDate, password FROM accounts WHERE email = ?');
$stmt->execute([$username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
// Verify the provided password against the hashed password stored in the database
if (password_verify($password, $user['password'])) {
// User logged in successfully
$response = array(
'success' => true,
'message' => 'Login successful',
'user' => array(
'id' => $user['id'],
'userToken' => $user['userToken'],
'firstname' => $user['firstname'],
'lastname' => $user['lastname'],
'email' => $user['email'],
'creationDate' => $user['creationDate']
)
);
} else {
$response = array('success' => false, 'message' => 'Invalid credentials');
}
} else {
$response = array('success' => false, 'message' => 'User not found');
}
} catch (PDOException $e) {
$response = array('success' => false, 'message' => 'Error retrieving user information');
}
} else {
$response = array('success' => false, 'message' => 'Username and password are required');
}
// Send JSON response
header('Content-Type: application/json');
echo json_encode($response);
}
?>
I’ve ensured that the SMTP configuration for Gmail is correct in the sendmail function, and I’ve also checked for any exceptions during the email sending process. However, the emails are not being delivered.
I suspect there might be an issue with the SMTP settings or some other configuration. Could someone please review the code and help me identify what might be causing this problem? Are there any common pitfalls with PHPMailer and Gmail SMTP that I might be missing?
Thanks in advance for any assistance!