PHPMailer根本不发送

时间:2017-10-24 03:26:32

标签: php smtp phpmailer

PHPMailer发送问题:

我一直在按照教程尝试通过PHPMailer和SMTP发送电子邮件,但它不发送,我不知道为什么......也许我的逻辑关闭或其他什么?

它只输出最后一条消息$ msg ="请再试一次!",并删除所有输入的表单字段。

这是我的PHP代码:

<?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
 ?>

我的HTML代码:

 <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>

1 个答案:

答案 0 :(得分:1)

尝试此操作以显示错误消息

if(!$mail->send()) {
    $msg = "Mailer Error: " . $mail->ErrorInfo;
} else {
    $msg = "Your form has been submitted, thank you. I will reply very soon";
}