HTML:从文本字段中获取价值并通过电子邮件发送

时间:2016-05-30 04:28:06

标签: javascript html twitter-bootstrap

我正在使用bootstrap来创建输入字段。当有人点击"提交"按钮我希望将值(如果它们有效)通过电子邮件发送给我自己。我甚至无法确保它们有效。以下是我的代码

<form action="tryjs_submitpage.htm" onsubmit="return myFunction()">
    <fieldset class="form-group">
        <label for="name">Name*:</label>
        <input type="text" class="form-control" id="usr" placeholder="Name">
     </fieldset>

     <fieldset class="form-group">
         <label for="email">Email Address*:</label>
         <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
     </fieldset>

     <fieldset class="form-group">
         <label for="company">Company:</label>
         <input type="text" class="form-control" id="company" placeholder="Company Name">
      </fieldset>

      <fieldset class="form-group">
          <label for="message">Message*:</label>
          <textarea class="form-control" rows="5" id="message" placeholder="Message"></textarea>
      </fieldset>

      <button type="submit" class="btn btn-primary">Submit</button>
</form>

<script>
function myFunction() {
    var name = document.getElementById("Name").value;
    var email = document.getElementById("Email").value.indexOf("@");
    var company = document.getElementById("company").value;
    var message = document.getElementById("message").value;

    submitOK = "true";

    if (name.length == 0) {
        alert("You must enter your name");
        submitOK = "false";
    } 

    if (email == -1) {
        alert("Not a valid e-mail!");
        submitOK = "false";
    }

    if (message.length == 0) {
        alert("You must enter a message");
        submitOK = "false";
    }

    if (submitOK == "false") {
        return false;
    }
}
</script>

我从here修改了脚本,但是当我点击提交时,它显示tryjs_submitpage.htm不存在。显然这是一个问题,但我似乎无法在任何地方找到tryjs_submitpage.htm来使其发挥作用。此外,我想知道是否有办法触发包含适当信息的电子邮件发送到我的个人电子邮件。谢谢你的帮助!

4 个答案:

答案 0 :(得分:0)

你的代码中有一点错误,

参数document.getElementById是元素id:

更改代码:

var name = document.getElementById("Name").value;
var email = document.getElementById("Email").value.indexOf("@");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;

对此:

var name = document.getElementById("usr").value;
var email = document.getElementById("exampleInputEmail1").value.indexOf("@");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;

答案 1 :(得分:0)

出于安全原因,您无法使用javascript直接发送电子邮件。 假设JavaScript中有一项功能可以发送电子邮件。一些恶意编码器可以编写脚本,以便在您访问其页面时立即将电子邮件发送到某个地址。这将在您不知情的情况下向某些第三方透露您的电子邮件地址。他们将开始在您的邮箱中填写大量垃圾邮件!但是,有如下所述的替代方案。 link

但是,您可以打开用户的邮件客户端:

<form action="" onsubmit="sendMail(); return false">
...
...
<button type="submit" class="btn btn-primary">Submit</button>
</form>

<script>
function sendMail() {
    var link = "mailto:me@abc.com"
             + "?cc=myCCaddress@example.com"
             + "&subject=" + escape("This is my subject")
             + "&body=" + escape(document.getElementById('myText').value)
    ;
    window.location.href = link;
}
</script>

答案 2 :(得分:0)

您无法直接从浏览器发送邮件,但您可以使用第三方技术(如http://www.emailjs.com/)或使用php本机邮件功能创建.php文件来发送邮件。

以下是处理邮件发送的HTML,JS(Jquery AJAX)和PHP文件。

在这种情况下,PHP脚本处理电子邮件验证,但您也可以在向服务器发送POST请求之前使用HTML require或JS regex在客户端进行检查

HTML

<form method="POST" action="" id="contactform">
  <p>
   <label for="name">Your Name</label>
   <input type="text" name="name" class="input" >
  </p>
  <p>
   <label for="email">Your Email</label>
   <input type="text" name="email" class="input">
  </p>
  <p>
   <label for="message">Your Message</label>
   <textarea name="message" cols="88" rows="6" class="textarea" ></textarea>
  </p>
   <input type="submit" name="submit" value="Send your message" class="button transition">
</form>

JS(JQuery)

var $contactform = $('#contactform'),
    $success = 'Your message has been sent. Thank you!',
    $url = 'link to the hosted php script';

$contactform.submit(function(e) {
  $.ajax({
    type: 'POST',
    url: $url,
    data: $(this).serialize(),
    dataType: "json",
    xhrFields: {
        withCredentials: true
    }
  })
  .done(function(msg) {
    console.log(msg)
    if (msg.success == true) {
      response = '<div class="success">' + $success + '</div>';
    }
    else {
      response = '<div class="error">' + msg.errors + '</div>';
    }

    // Hide any previous response text.
    $('.error, .success').remove();

    // Show response message.
    $contactform.prepend(response);
  })
  .fail(function(msg) {
    console.log(msg)
  });
  e.preventDefault();
});

PHP

<?php
  // Array to hold validation errors and response data.
  $errors = array();
  $data = array();

  // Validate the variables
  // if any of these variables don't exist, add an error to our $errors array
  $name = $_POST['name'];
  $email = $_POST['email'];
  $msg = $_POST['message'];

  $nospace_name = trim($_POST['name']);
  $nospace_email = trim($_POST['email']);
  $nospace_message = trim($_POST['message']);

  // * wont work in FF w/ Allow-Credentials
  //if you dont need Allow-Credentials, * seems to work
  header('Access-Control-Allow-Origin: *');
  //if you need cookies or login etc
  header('Access-Control-Allow-Credentials: true');
  if ($this->getRequestMethod() == 'POST') {
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 604800');
    //if you need special headers
    header('Access-Control-Allow-Headers: x-requested-with');
  }

  if (empty($nospace_name))
    $errors['name'] = "Name field is required.";

  if (empty($nospace_email))
    $errors['email'] = "Email field is required.";

  if (empty($nospace_message))
    $errors['message'] = "I would love to see your message.";

  if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
    $errors['bad_email'] = "Please enter a valid email address";


  // if there are any errors in our errors array, return a success boolean of false
  if (!empty($errors)) {
    // if there are items in our errors array, return those errors
    $data['success'] = false;
    $data['errors']  = $errors;
  }
  else {
    // if there are no errors process our form, then return a message

    // prepare message to be sent
    $to = "admin@example.com";
    $subject = "Website Contact Form: ".$name;

    $headers = "From: noreply@example.com\n"; // email address the generated message will be from. Recommend using something like noreply@yourdomain.com.
    $headers .= "Reply-To: ".$email;

    // build the message
    $message = "Name: ".$name."\n\n";
    $message .= "Email: ".$email."\n\n";
    $message .= "Message: ".$msg;

    // send it
    $mailSent =  mail($to, $subject, $message, $headers);

    // check if mail was sent successfully
    if (!$mailSent) {
      $errors['unknown_error'] = "Something went wrong...Please try again later";
      $data['success'] = false;
      $data['errors']  = $errors;
    }
    else {
      // show a message of success and provide a true success variable
      $data['success'] = true;
      $data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
    }

  }

  // return all our data to an AJAX call
  echo json_encode($data);
 ?>

答案 3 :(得分:0)

我的建议是不要自己进行表单验证,只需让浏览器执行即可。您需要将电子邮件输入中的input类型更改为email,然后您需要将required属性添加到您想要的每个属性中。

这种方式不是使用JavaScript,而是使用符合标准的HTML。

然后,由于您无法直接从浏览器发送电子邮件,因此您需要第三方服务来发送电子邮件,例如Formspree。或者,您可以编写用于发送电子邮件的服务器端脚本,但使用服务要容易得多。

以下是最终代码:

<form action="https://formspree.io/your.email.here@example.com">
        <fieldset class="form-group">
            <label for="usr">Name*:</label>
            <input type="text" class="form-control" id="usr" placeholder="Name" name="message" required="required">
         </fieldset>
    
         <fieldset class="form-group">
             <label for="exampleInputEmail1">Email Address*:</label>
             <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" name="email" required="required">
         </fieldset>
    
          <fieldset class="form-group">
              <label for="message">Message*:</label>
              <textarea class="form-control" rows="5" id="message" placeholder="Message" name="message" required="required"></textarea>
          </fieldset>
    
          <button type="submit" class="btn btn-primary">Submit</button>
    </form>

如果您想使用Formspree并让访问者输入他们的公司名称,您可以通过给公司名称字段命名为“主题”来破解它,Formspree将转发到您的电子邮件以及其他字段。