Cannot send email in phpMailer with ReactJs as frontend application - php

I intend to send an email to the user that registers their account with an account verification link, so in that way I can keep them logged in the session, therefore to achieve that, I'm using phpMailer as email configuration in PHP, and as for frontend I'm using React.
However, even though the code is fine, the setup is alright, I even set up an application password for my project (less secure apps have been entirely disabled, and I'm using Gmail), but the email doesn't send at all.
I am wondering what could be the problem, maybe it could be an issue I overlooked in the code, or something wrong with the setup in general? I will attach the code lines from both React and PHP so you can take a look, thank you in advance!
P.S. I made use of send_email function due to getting undefined variable $to_email, despite it being defined in signup.php, and replaced the email and app password with generic names to cover them.
React (the handleSubmit function)
const handleSignUpSubmit = (event) => {
event.preventDefault();
const register_account = {
first_name: first_name,
last_name: last_name,
company: company,
email: email,
phone_number: phone_number,
password: password,
confirm_password: confirm_password,
};
axios
.post("http://localhost/bachelor_exam/signup.php", register_account)
.then((response) => {
if (response.data) {
navigate("/emailconfirm");
}
})
signup.php (where the data starts to be inserted in database)
} else {
$q=$db->prepare("INSERT INTO users(user_id, first_name, last_name, company, email, phone_number, password, forgot_password, token, verified) VALUES(:user_id, :first_name, :last_name, :company, :email, :phone_number, :password, :forgot_password, :token, :verified)");
$q->bindValue(":user_id", null);
$q->bindValue(":first_name", $firstName);
$q->bindValue(":last_name", $lastName);
$q->bindValue(":company", $company);
$q->bindValue(":email", $email);
$q->bindValue(":phone_number", $phoneNumber);
$q->bindValue(":password", $passwordHash);
$q->bindValue(":forgot_password", $forgotPass);
$q->bindValue(":token", $token);
$q->bindValue(":verified", false);
$q->execute();
$id = $db->lastInsertId();
$to_email = $email;
$subject = "Nuub - Account Confirmation";
$message = "Welcome to Nuub, click on the following link to verify your account:
<a href='http://localhost/bachelor_exam/confirm_account.php?token=$token'>Confirm your account</a>";
require_once("./emailVerification/send_email.php");
send_email($to_email, $subject, $message);
$_SESSION["first_name"] = $firstName;
header("Content-type: application/json");
http_response_code(200);
echo json_encode($_SESSION["first_name"]);
exit();
}
}
the PHPMailer configuration
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
function send_email($to_email, $subject, $message){
if($_SERVER["HTTP_REFERER"] === "http://localhost:3000/"){
require '../emailVerification/include/Exception.php';
require '../emailVerification/include/PHPMailer.php';
require '../emailVerification/include/SMTP.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
//Server settings
$mail->SMTPDebug = false; // 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#gmail.com'; // SMTP username
$mail->Password = 'app_password'; // SMTP password
// $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption;
`PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption;
`PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 465;
// $mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('email#gmail.com', 'Nuub');
$mail->addAddress($to_email, 'user'); // Add a recipient
// $mail->addAddress('ellen#example.com'); // Name is optional
// $mail->addReplyTo('DUMMY_EMAIL_HERE_XXXXXXXXXXXXXXXXXX', 'Information');
// $mail->addCC('cc#example.com');
// $mail->addBCC('bcc#example.com');
// 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 = $subject;
$mail->Body = $message;
$mail->isHTML(true);
// $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
if(!$mail->send()){
echo json_encode("Mail not sent" . $mail->ErrorInfo);
} else {
echo json_encode("Email has been sent");
}
} catch (Exception $e) {
echo json_encode("Message could not be sent. Mailer Error: {$mail->ErrorInfo}");
}
}
}

Related

This ite can't be reached (PHP mailer)

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.

PHPMailer dynamic mail recipient insertion

We all know how to implement PHPMailer within a project and its use is great, but I need something more, after entering the necessary parameters in order to make everything work.
I need a form to change the email address of the recipient who will receive the email, how can I do?
code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // 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 = 'xxx#gmail.com'; // SMTP username
$mail->Password = 'xxx'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('xxx', 'xxx'); // Sender email and name
$mail->addAddress('xxx'); // Reciver email
// if you want to send email to multiple users, then add the email addresses you which you want to send.
//$mail->addAddress('reciver2#gmail.com');
//$mail->addAddress('reciver3#gmail.com');
//For Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // You can specify the file name
//Content
$mail->isHTML(true);// Set email format to HTML
$mail->Subject = 'Oggetto dell email'; // Subject of the email
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>

gmail disabled my account for sending too many emails through PHPMailer library

I'm using PHPMailer library to send 100 emails to my customers after every 5 mints. It was sending successfully. but when i had sent about 800 emails, gmail disabled my account because spamming or sending unwanted content. I was sending different email to every customer. Now i'm worried is there anything else to send too many emails for email marketing. here is my code
$sql="SELECT * FROM send_user_link LIMIT 100";
$result=$conn->query($sql);
while($row=$result->fetch_assoc()){
$email=$row['email'];
$name=$row['name'];
$id=$row['id'];
$code=$row['code'];
$e_subject="Support";
$msg="<h5>how are you doing??</h5>";
send_email_to_users($conn, $id, $email, $e_subject, $msg, $name);
}
function send_email_to_users($conn, $user_id, $to_email, $subject, $msg, $name){
$mail = new PHPMailer(); // Passing `true` enables exceptions
//Server settings
$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 = 'myacount#gmail.com'; // SMTP username
$mail->Password = '*******'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('myaccount#gmail.com', 'Support');
$mail->addAddress($to_email, $name); // 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');
//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 = $subject;
$mail->Body = $msg;
$mail->AltBody = 'how are you doing??';
$user_id = mysqli_real_escape_string ($conn, $user_id );
if ($mail->send()) {
echo 'Message has been sent';
}
else{
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
}
Please help me to know is there anything to send to many emails without getting disabled from email service providers. Thank you

How to send a longer mail with php

I have been trying to send emails with PHP, but whenever the message gets too long the mail isn't sent.
This is what I have so far:
$name= $_POST["name"];
$email= $_POST["email"];
$comment= $_POST["text"];
$msg= "Naam: " . $name . "\r\nEmail: " . $email . "\r\nBericht: " . $comment;
mail("test.test#live.nl", "Website", $msg);
I don't recommend that you do it this way, since emails can get spam.
I recommend you use phpmailer.
I leave you an example:
try {
$mail = new PHPMailer(true);
//Server settings
$mail->isSMTP();
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#example.com'; // SMTP username
$mail->Password = 'pass'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
//Recipients
$mail->setFrom('example#example.com', 'name');
if(is_array($this->Emails)){
foreach($this->Emails as $email){
$mail->addAddress($email); // Add a recipient
}
}
else{
$mail->addAddress($this->Emails); // Add a recipient
}
if(isset($this->Attachments)){
if(is_array($this->Attachments)){
foreach($this->Attachments as $Attachment){
$mail->addAttachment($Attachment); // Add attachments
}
}
else{
$mail->addAttachment($this->Attachments); // Add attachments
}
}
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $this->Subject;
$mail->Body = $this->Body;
$mail->send();
return true;
I'm recommending this because your method in sending an email in PHP is very out dated now, it will save you many headaches.
Use Composer
Install Swiftmailer like this composer require swiftmailer/swiftmailer
Much easier to manage emails

Is sending email from yahoo's email address possible using gmails's smtp in phpmailer

<?php
require ("PHPMailer-master/PHPMailerAutoload.php");
$mail = new PHPMailer;
if(isset($_POST['submit']))
{
$email_query = "select email1,email2 from tbl_contacts where id = '1'";
$query_result = mysql_query($email_query);
$value = mysql_fetch_array($query_result);
$primary_email = $value['email1'];
$CC = $value['email2'];
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$mail->IsSendmail(); // Set mailer to use SMTP
$mail->Host = "smtp.google.com"; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $email; // SMTP username
//$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->setFrom($email, $name);
//$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addAddress($primary_email); // Name is optional
$mail->addReplyTo($email, '');
$mail->addCC($CC);
//$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 = $subject;
$mail->Body = $message;
$mail->AltBody = $message;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
redirect('/contact.php?message=Your+Message+Has+Been+Sent!', 'location');
}
}
?>
I am using gmail's smtp and it works fine if I send an email with a gmail account but when I send an email with an yahoo account it displays a success message but the message does not get delivered. Is it possible to send email from yahoo's email using gmail' smtp? If yes, how can I do it? And if not, how can I solve the problem?
In general,
avoid declaring incorrect identity.
This might be possible from technical aspect; however in 2016 most email systems tend to protect themself by using multip. techniques - like SPF, DKIM and DMARC and that is both for sending and evaluating received emails.
If this is true for more and more email systems and ESP's it's not hard to imagine what ESP giants like Yahoo, GMAIL and others are doing to express their hate on incorrectly declared identities (mark as spam, reject at SMTP handshake level, silently discard...).
In your case displaying success message only mean that your mail is received on MTA side for further processing, not anything about it's future.

Categories