PHPMailer send issue:
I have been following a tutorial to try and send an email via PHPMailer and SMTP, However it is not sending and I am not sure why... maybe my logic is off or something else?
It just outputs the last message $msg = "Please try again!", and removes all form fields entered.
Here is my PHP code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$msg = ""; //message variable
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['message'];
//var_dump($_FILES);
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] !="") {
$file = "attachments/" . basename($_FILES['attachment']['name']);
move_uploaded_file($_FILES['attachment']['tmp_name'], $file);
} else{
$file = " ";
} // end of file attachment
//echo $file;
//send via SMTP
$mail = new PHPMailer();
$mail->Host = "smtp.gmail.com";
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Username = "myemail@gmail.com";
$mail->Password = "mypassword";
$mail->SMTPSecure = "tls"; //ssl
$mail->Port = 465; //587
$mail->addAddress("myemail@gmail.com");
$mail->setFrom($email, $name);
$mail->Subject = $subject;
$mail->isHTML(true);
$mail->Body = $message;
$mail->addAttachment($file);
if ($mail->send())
$msg = "Your form has been submitted, thank you. I will reply very soon";
else
$msg = "Please try again!";
} // end of post submit
?>
my HTML code:
<div class="container" style="margin-top: 80px">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3">
<img class="sendemail mb-4 mx-auto d-block" src="./images/email.svg">
<h2 class="text-center mb-5">Send an email</h2>
<?php if ($msg != "") echo $msg;?>
<form method="post" action="sendmail-v2.php" enctype="multipart/form-data">
<input type="text" class="form-control" name="name" placeholder="name">
<input type="text" class="form-control" name="subject" placeholder="subject">
<input type="email" class="form-control" name="email" placeholder="email">
<textarea class="form-control" name="message" placeholder="enter message here" rows="3"></textarea>
<input type="file" name="attachment" class="file-input form-control d-block mb-4" id="attachment-file">
<!-- display pathfile selected to user -->
<!-- <script type="text/javascript">
document.getElementById('attachment-file').onchange = function () {
alert('Selected file: ' + this.value);
};
</script> -->
<input class="btn btn-primary" type="submit" name="submit" value="send email">
</form>
</div>
</div>
</div>