OK 400
OK 400

Reputation: 831

Sending email in Javascript

According to Sending emails with Javascript, one way to do it is the following:

function sendMail() {
    var link = "mailto:[email protected]"
             + "[email protected]"
             + "&subject=" + encodeURIComponent("This is my subject")
             + "&body=" + encodeURIComponent(document.getElementById('myText').value)
    ;
    window.location.href = link;
}

However I'm trying to personalize it, sending emails with variables. I did this:

function sendMail(subject="test", body, mail="[email protected]") {
  var link = `mailto:${mail}`
           + "&subject=" + encodeURIComponent(`${subject}`)
           + "&body=" + encodeURIComponent(`${body}`)
  ;
  window.location.href = link;

But, when sending the email, I achieve this fail:

fail (image)

It seems like it is not recognizing each variable. How to solve it?

Upvotes: 1

Views: 1375

Answers (3)

Eklavya Jain
Eklavya Jain

Reputation: 47

Just try this code for sending email. I am sure it will work..

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://smtpjs.com/v3/smtp.js"></script>  
    <script type="text/javascript">
        function sendEmail() {
            Email.send({
                Host: "smtp.gmail.com",
                Username : "<sender’s email address>",
                Password : "<email password>",
                To : '<recipient’s email address>',
                From : "<sender’s email address>",
                Subject : "<email subject>",
                Body : "<email body>",
            })
            .then(function(message){
                alert("mail sent successfully")
            });
        }
    </script>
</head>
<body>  
    <form method="post">
        <input type="button" value="Send Email" onclick="sendEmail()"/>
    </form>  
</body>

And just remember if you are using JavaScript in any other file then just link it will your HTML file! And this is the not fully coded by me I have done some research from internet.

Upvotes: 0

Hugo
Hugo

Reputation: 131

The query string should be start with ? not &

change &subject to ?subject

it should be //[email protected]?subject=blahblahblah&body=testtest

Upvotes: 1

Elikill58
Elikill58

Reputation: 4938

The link have to be like that :

var link = `mailto:${mail}`
           + "?subject=" + encodeURIComponent(`${subject}`)
           + "&body=" + encodeURIComponent(`${body}`);

Upvotes: 1

Related Questions