简体   繁体   English

发送电子邮件,html > jQuery > PHP

[英]Sending email, html > jQuery > PHP

I'm trying to send an email to myself with the text that has been entered in the textbox.我正在尝试向自己发送一封电子邮件,其中包含在文本框中输入的文本。

<form class="form align-center" id="mailchimp">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="newsletter-label font-alt">
                Stay informed with our newsletter
            </div>
            <div class="mb-20">
                <input placeholder="Enter Your Email" class="newsletter-field form-control input-md round mb-xs-10"
                    name="emaill" type="email" pattern=".{5,100}" required aria-required="true">
                <button type="submit" aria-controls="subscribe-result" id="submit_btnn"
                    class="btn btn-mod btn-medium btn-round mb-xs-10">
                    Subscribe
                </button>
            </div>
            <div class="form-tip">
                <i class="fa fa-info-circle"></i> Please trust us, we will never send you spam
            </div>
            <div id="subscribe-result" role="region" aria-live="polite" aria-atomic="true"></div>

After that I catch it in Js之后我在Js中抓住了它

$(document).ready(function(){
    $("#submit_btnn").click(function(){
        //get input field values
        var user_email = $('input[name=emaill]').val();
        //simple validation at client's end
        var proceed = true;
        //we simply change border color to red if empty field using .css()
        if (user_email == "") {
            $('input[name=email]').css('border-color', '#e41919');
            proceed = false;
        }
        //everything looks good! proceed...
        if (proceed) {
            //data to be sent to server
            post_data = {
                'userEmail': user_email
            };
            console.log(post_data);
            //Ajax post data to server
            $.post('nieuwsbrief.php', post_data, function(response){
                //load json data from server and output message     
                if (response.type == 'error') {
                    output = '<div class="error">' + response.text + '</div>';
                }
                else {               
                    output = '<div class="success">' + response.text + '</div>';
                }      
                $("#subscribe-result").hide().html(output).slideDown();
            }, 'json');
            
        }
        
        return false;
    });
    
    //reset previously set border colors and hide all message on .keyup()
    $("#contact_form input, #contact_form textarea").keyup(function(){
        $("#contact_form input, #contact_form textarea").css('border-color', '');
        $("#subscribe-result").slideUp();
    });
    
});

After that I want to use the Ajax post to send it to my php file之后我想使用 Ajax 帖子将其发送到我的 php 文件

<?php
if($_POST)
{
    echo '<script>console.log($_POST["userEmail"])</script>';
    $to_Email       = "mathias@wizewolf.com"; //Replace with recipient email address
    $subject        = 'Message from website '.$_SERVER['SERVER_NAME']; //Subject line for emails
    echo '<script>console.log(to_Email)</script>';
    
    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    
        //exit script outputting json data
        $output = json_encode(
        array(
            'type'=>'error', 
            'text' => 'Request must come from Ajax'
        ));
        
        die($output);
    } 
    
    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userEmail"]))
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
        die($output);
    }

    //Sanitize input data using PHP filter_var().
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Message     = "d";
    
    $user_Message = str_replace("\&#39;", "'", $user_Message);
    $user_Message = str_replace("&#39;", "'", $user_Message);
    
    //additional php validation
    if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
        die($output);
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
        die($output);
    }
    if(strlen($user_Message)<5) //check emtpy message
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
        die($output);
    }
    
    //proceed with PHP email.
    $headers = 'From: '.$user_Email.'' . "\r\n" .
    'Reply-To: '.$user_Email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    
    $sentMail = @mail($to_Email, $subject, $user_Message . "\r\n\n"  .'-- '.$user_Name. "\r\n" .'-- '.$user_Email, $headers);
    
    if(!$sentMail)
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
        die($output);
    }else{
        $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .'! Thank you for your email'));
        die($output);
    }
}
?>

With the console log, I've found out that until the start of the PHP file everything works.通过控制台日志,我发现在 PHP 文件开始之前一切正常。 After that... not so much.在那之后……没那么多了。 All the tips and info are appreciated.感谢所有的提示和信息。

Instead of using jQuery and PHP, you could use STMP.js.您可以使用 STMP.js,而不是使用 jQuery 和 PHP。 I don't know how to answer this question with jQuery or PHP, but I know how to send emails with SMTP.我不知道如何用 jQuery 或 PHP 回答这个问题,但我知道如何用 SMTP 发送电子邮件。 I made an example on JSFiddle below.我在下面的 JSFiddle 上做了一个例子。 But, this might not work on JSFiddle for security reasons.但是,出于安全原因,这可能不适用于 JSFiddle。

JSFiddle JSFiddle
https://jsfiddle.net/Yeet45687564/9prs4j2a/21/ https://jsfiddle.net/Yeet45687564/9prs4j2a/21/

// the javascript code below is also found on JSFiddle

let subject;
let body;

function setValues() {

  // sets the values of the subject and body
  subject = document.getElementById("emailSubject").value;
  body = document.getElementById("emailBody").value;
  
}

function send() {
  setValues();
  
  // sends the email
  Email.send({
    Host: "smtp.gmail.com",
    Username: "<sender's email address>",
    Password: "<your email password>",
    To: "<recipient's email address>",
    From: "<sender’s email address>",
    Subject: subject,
    Body: body,
  }).then(
  
    // displays a message if the email was sent
    message => alert("Your Email was sent.")
    
  );
  
}

If you can't get this working, there is an SMTP tutorial on Pepipost. 如果你不能让它工作,Pepipost 上有一个 SMTP 教程。

https://pepipost.com/tutorials/how-to-send-emails-with-javascript/ https://pepipost.com/tutorials/how-to-send-emails-with-javascript/

But, using SMTP could be a huge security issue.但是,使用 SMTP 可能是一个巨大的安全问题。 Anyone who uses the inspect element on your website will be able to get your email password, unless you can block them from inspecting it and viewing the page source.任何在您网站上使用检查元素的人都将能够获得您的电子邮件密码,除非您可以阻止他们检查和查看页面源代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM