PHPMailer() ajax 请求

Posted

技术标签:

【中文标题】PHPMailer() ajax 请求【英文标题】:PHPMailer() ajax request 【发布时间】:2014-11-14 09:33:17 【问题描述】:

在我使用 php 和 $.ajax() 验证表单并将邮件发送到我自己的邮件地址时,我的发件人是我自己的 gmail 地址,主题是用户名和表单中的电子邮件。基本上,我希望网站通知我用户给我留言以及他的姓名和地址,我可以回复他。当我尝试发送时,我收到一个错误。 我从 PHPMailer 示例中获取了脚本,但我无法弄清楚邮件正文应该在哪里。我有 php 文件:

<?php

error_reporting(E_ALL);
 ini_set('display_errors',true);

// require_once 'class.phpmailer.php'; 需要'PHPMailerAutoload.php';

sleep(1);

 $mail_reg = '/^(?i)(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\  [[0-9]1,3\.[0-9]1,3\.[0-9]1,3\.[0-9]1,3\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]2,))$/';

$return = array();
$mesaj = '';


if ($_SERVER['REQUEST_METHOD'] === 'POST') 


    if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) 

      $mesaj = "Please enter your name!";
     // $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

     elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg,   $_POST['inputEmail'])) 

      $mesaj = "Please enter your e-mail!";
    //  $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

     elseif (empty($_POST['inputMess'])) 

      $mesaj = "Please tell us something";
     // $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

     else 

      $mail = new PHPMailer();
      $mail->IsSMTP();          
      $mail->SMTPDebug  = 2;
      $mail->Debugoutput = 'html';
      $mail->Host = "smtp.gmail.com";
      $mail->Port = 587;          
      $mail->SMTPSecure = "tls";
      $mail->SMTPAuth   = true;          
      $mail->Username = "tavitudor124@gmail.com";
      $mail->Password = "**********";
      $mail->SetFrom('tavitudor124@gmail.com' , 'First Last');         
      $mail->Subject = $_POST['inputName'].'/'.$_POST['inputEmail'].'wrote';
      //$mail->MsgHTML($body);
      $address = 'tavi_tudor@yahoo.com';
      $mail->AddAddress($address, "John Doe");
      $mail->Body = $_POST['inputMess'];

      if (!$mail->Send()) 
        $mesaj = 'The message cannot be delivered, please try again later!';
        $return['msg'] = 'The message cannot be delivered, please try again later!';
        echo json_encode($return);
        exit();

       else 

      $mesaj = 'Thank you for getting in touch. We will contact you!';
     // $return["error"] = false;
      $return["msg"] = 'Thank you for getting in touch. We will contact you! '.$mail-  >ErrorInfo;
      echo json_encode($return);
       exit();
     
    
  


  ?>

   <!DOCTYPE html>

<html lang="en">
 <head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
   <title>NRDC Environmental N.G.O.</title>
  <link href="css/bootstrap.css" rel="stylesheet">

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script src="js/bootstrap.min.js"></script>
    <script src="js/marin.js"></script>
  </head>

<div class="site-wrapper">

  <div class="site-wrapper-inner">

    <div class="cover-container">

      <div class="masthead clearfix">
        <div class="inner">
          <h3 class="masthead-brand">NRDC<br />Save our Planet  O.N.G.</h3>
          <ul class="nav masthead-nav">
            <li><a href="index.html">Home</a></li>
            <li><a href="gallery.html">Gallery</a></li>
            <li class="active"><a href="contact.php">Contact</a></li>
            <li><a href="#">Join Us</a></li>
          </ul>
        </div>
      </div>

      <div class="inner cover">
          <div class="row">
            <div class="col-xs-12" style="text-align:center;font-size:22px;">

             <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                <div class="form-group">
                    <label for="inputName">Your name</label>
                    <input type="text" name="inputName" class="form-control"   id="inputName" placeholder="Name">
                </div>

                <div class="form-group">
                    <label for="inputEmail">Your e-mail</label>
                    <input type="text" name="inputEmail" class="form-control" id="inputEmail" placeholder="E-mail">
                </div>

                <div class="form-group">
                    <label for="inputMess">Your message for us</label>
                    <textarea name="inputMess" class="form-control" id="inputMess">  </textarea>
                </div>

                <button type="submit" name="send" class="btn btn-default">Send</button>
              </form>

              <div id='mess'> </div>

            </div>


          </div>


      </div>

      <div class="mastfoot">
        <div class="inner">
          <p id="footer">©All rights reserved to NRDC, by TaoAppz</p>
        </div>
      </div>

    </div>

  </div>

</div>

JS

$(document).ready(function() 

 var email_reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]1,3\.[0-9]1,3\.[0-9]1,3\.[0-9]1,3\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]2,))$/i;   

$('form').submit(function(event) 

  event.preventDefault();

  if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) 

    alert('Please enter your name');

   else if (!email_reg.test($('#inputEmail').val())) 

    alert('Please enter a valid e-mail adress');

   else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) 

    alert('Please tell us something');

   else 

    var formData = $('form').serialize();
    submitForm(formData);

  

)


function submitForm(formData) 

    $.ajax(

        type: 'POST',
        url: $('form').action,
        data: formData,
        dataType: 'json',
        cache: false,
        timeout: 7000,
        beforeSend: function() 

      $('#mess').text('Processing...');

    ,        
    success: function(data) 


                $('#mess').text(data.msg);              

        ,
        error: function(XMLHttpRequest, textStatus, errorThrown) 


                $('#mess').text('Error! ' + textStatus + ' ' + errorThrown  + ' ' + 'Please try again later!');

        ,
        complete: function(XMLHttpRequest, status) 

            //$('form')[0].reset();


        

    )



  )

【问题讨论】:

你遇到了什么错误? 我得到messaje'无法发送'第一个if语句并且json文件似乎没问题。我提到我在本地主机上工作。 您是否从您的 gmail 授予了适当的访问权限? 不,我不知道我必须这样做。它在我的gmail帐户设置中吗?我会找找告诉你的 当您尝试从客户端发送邮件时,请保持您的邮件处于登录状态并要求您提供一些访问权限,启用它 【参考方案1】:

这是我在 php 中包含的错误,并且 '$mail->Debugoutput = 'html' 创建了被传递为 JSON 的 html 输出。

所以我从 PHPMailer 中取出了调试模式,现在我有了一个使用 ajax 和 PHPMailer 的工作良好的联系表单。感谢您的帮助

【讨论】:

以上是关于PHPMailer() ajax 请求的主要内容,如果未能解决你的问题,请参考以下文章

带有SMTP的AJAX jQuery JSON PHPMailer

composer的安装以及laravel框架的安装

警告:require_once(Composer/PHPMailer/vendor/phpmailer/phpmailer/src/autoload.php):无法打开流:没有这样的文件或目录

2019 无法调用未创建 PHPMailer 版本 6.0.7 实例的新 PHPMailer

phpmailer无法发送电子邮件

PHPMailer:替换默认的messageID