简体   繁体   中英

How can I use JavaScript to send emails instantly?

I have been trying to figure out a way to send emails with JavaScript. So the first thing I did was went to Google and looked up if this is possible. I found out you can use the code below to send JavaScript emails.

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
    </head>
    <body>
        <form method="post">
            <input type="text" id="emailSubject" placeholder="Type your 
            subject... "/>
            <input type="text" id="emailBody" placeholder="Type something... "/>
            <button onclick="send()">
                Send
            </button>
        </form>
    </body>
    <script type="text/javascript" src="https://smtpjs.com/v3/smtp.js"></script>
    <script type="text/javascript" src="script.js"></script>
</html>

script.js

const emailSubject = document.getElementById("emailSubject").value;
const emailBody = document.getElementById("emailBody").value;

function send() {
    Email.send({
    Host: "smtp.gmail.com",
    Username: "myemail@gmail.com",
    Password: "*******",
    To: "anotheremail@gmail.com",
    From: "myemail@gmail.com",
    Subject: emailSubject,
    Body: emailBody,
    }).then(
        message => alert("Sent successfully.")
    );
}

Why didn't this work? I check this code for any misspelled words, and found none. So can anyone help with this?

Looking at the tutorial there is a key difference between your implementation and the one provided. Where you are using <button> the example uses <input type="button"> like below:

<input type="button" value="Send Email" onclick="send()"/>

Key difference is the button you are using is submitting the form element and refreshing the page so the send() function is never run.

With the above in place of the button the form is never submitted and the function is called.

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