如何通过emailjs发送电子邮件?

时间:2019-10-11 22:06:25

标签: javascript html forms

因此,我一直在尝试为客户设置联系页面,而我目前正在使用emailjs进行此操作,但是在发送测试电子邮件以查看其是否有效时,它总是会出现错误。

我已经尝试过访问emailjs网站,以找出问题所在,但我什么也没想到。

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="css/styles2.css">
        <link rel="stylesheet" href="css/newheader.css">
        <link rel="stylesheet" href="css/contact.css">
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <script type="text/javascript" src="https://cdn.emailjs.com/sdk/2.3.2/email.min.js"></script>
        <script type="text/javascript">
          (function(){
            emailjs.init("user_ID"); // i have the user id in the code I just didn't want to post it online
          })();
        </script>
        <script type="text/javascript">
           window.onload = function() {
                document.getElementById('contact-form').addEventListener('submit', function(event) {
                event.preventDefault();
                // generate the contact number value
                this.contact_number.value = Math.random() * 100000 | 0;
                emailjs.sendForm('contact_service', 'contact_template', this);
            });
        }
    </script>
    </head>

  <body>
     <header>
     {{>header_2}}
     </header>

      <form id="contact-form">
        <input type="hidden" name="contact_number">
        <label>Name</label>
        <input type="text" name="user_name">
        <label>Email</label>
        <input type="email" name="user_email">
        <label>Message</label>
        <textarea name="message"></textarea>
        <input type="submit" value="Send">
    </form>
    </body>
</html>

预期结果是发送测试电子邮件以使事情顺利进行,但由于某种原因它无法正常工作,出现了错误的请求,因此我不确定该怎么办。

1 个答案:

答案 0 :(得分:0)

发送电子邮件非常容易,您不需要插件。首先,让您准备好表格;将这些属性添加到表单中。

<form id="contact-form" method="POST" action="PHP/mailto.php">

现在是时候设置js脚本了:

// first things first you gotta listen to the submit event and stop it from 
// performing the 'action' which is redirecting the form data to the php
// file we are going to create.
document.getElementById('contact-form').addEventListener('submit', function(event){
  //this prevents the form from doing its default action: redirection
   event.preventDefault();
  // disable inputs so form can only be sent once
  $disabled_inputs = document.querySelectorAll('input, textarea');
  for(i = 0; i < $disabled_inputs.length; i++){
    $disabled_inputs[i].disabled = true;
  }
  // empty JSON object that will hold form data
  var data = {};
  //this function will loop through the data and collect the info on the inputs 
  // and text areas with a name attribute
    this.querySelectorAll('input[name], textarea[name]').forEach(function($input) {
     // this formats the data in a JSON object {inputname : inputvalue}
     $data[$input.getAttribute('name')] = $input.value;
  });
  // take a look at the console so you get used to the json format
  console.log($data);
  // this will store the data in a JSON object so you have to clean it to send 
  // it to the php file with a post variable set
  var json_upload = "your_php_postvariable=" + JSON.stringify($data);
  // open new ajax request
  var inquriry_request = new XMLHttpRequest();
  // declare ajax method and origin (look at the form element)
  inquriry_request.open("POST", "/PHP/mailto.php");
  // declare cleaned JSON format to PHP file
  inquriry_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  // send ajax request with data
  inquriry_request.send(json_upload);
  // this functions runs after ajax request loads response
  inquriry_request.onload = function(){
    // create new script element 
    scripter = document.createElement('script');
    // declare javascript type 
    scripter.type = 'text/javascript';
    // load script echoed from php file inside this tag 
    scripter.innerHTML = inquriry_request.responseText;
    // append script to body (this will cause script to run)
    document.querySelector('body').append(scripter);
  }
});

现在让我们设置mailto.php文件:

<?php 
 // run this function if post variable is set
 if(isset($_POST['your_php_variable']){
 // this while output an error log inside the /PHP/ directory
 error_log(0);
 // html email headers
 $headers = "From: Web Emails <your@email.com>\r\n";
 $headers .= "MIME-Version: 1.0\r\n";
 $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
 // php post variable loop input attributes
 var $php_post_var_loop = $_POST['your_php_variable'];
 $name = $php_post_var_loop['user_name'];
 $email = $php_post_var_loop['user_email'];
 $message = $php_post_var_loop['message'];
 // strings in php are appended by dots
 $email_text = "From: ". $name . "<br><br>".
 "Email: " . $email . "<br><br>".
 "Message: " . $message;

 // run if statement to check if php function ran to send mail
 if(@mail('your@email.com', 'Email Subject', $email_text, $headers)){
   // use this if you have to switch between single and double quotes
   // inside your js script
   $quo = '"';
   echo "//js code to run if mail sends!"
 } else {
   // use this if you have to switch between single and double quotes
   // inside your js script
   $quo = '"';
   echo = "//js code to run if mail does not send"
 } 
}
?>