简体   繁体   中英

Send an AJAX email in a Javascript funciton without using PHP

I was handed a website to work on and I'm not very familiar with AJAX. I was hoping there was a simple solution to the URL: portion of the Ajax in order to send an email. I'd rather not use a PHP script in place of what's already there but if needed I can.

This is for a website that's mostly bootstrapped with some simple HTML code and naming conventions are standard.

<script>
    $("#btnSend").click(function () {

        var email = $('#txtFromEmail').val();

        if (($('#txtName').val().length === 0) || (email.length === 0) ||
            ($('#txtSubject').val().length === 0) || ($('#txtBody').val().length === 0)) {
            alert("Please fill out all of the form.");
        } else {
            var emailModel = {
                Name: $('#txtName').val(),
                FromEmail: $('#txtFromEmail').val(),
                Subject: $('#txtSubject').val(),
                Body: $('#txtBody').val()
            };

            $.ajax({
                url: "@Url.Action("Contact", "Main")",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(emailModel),
                success: function (result) {
                    if (result.message.length == 0) {
                        alert("Message Sent Successfully!");
                    } else {
                        alert("Message failed to send. Please try again or call the Sports Hub");
                    }
                }
            });
        }
    });
</script>

Ajax can make HTTP requests. That is all.

If you want to send email then you'll need to either:

  • Use the user's email client (and not Ajax) which is highly unreliable
  • Make an HTTP request to a web service that will send the email

You could write the web service in PHP, or you could use a different programming language (you seem to be using ASP.NET so any ASP.NET compatible language will do), or you could find a third-party hosted service.

you can use an email web service to do this. i replaced my PHP page because it was a pain setting it up when i migrated from godaddy to aws. check out formspree. you will be able to integrate thru the front-end. on your first email you'll have to accept formspree emails, once you do, all other emails will be fwd to you.

There is no way you can send an email directly from Javascript.

Either you use php or open directly the mail client from the browser:

window.open('mailto:test@example.com');

If you want to pass more parameters you can use the following string:

window.open('mailto:test@example.com?body=body&subject=subject');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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