1

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

function sendMail() {
    var link = "mailto:me@example.com"
             + "?cc=myCCaddress@example.com"
             + "&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="test@gmail.com") {
  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?

Dominik
  • 6,078
  • 8
  • 37
  • 61
Omar
  • 1,029
  • 2
  • 13
  • 33
  • 4
    You're missing the `?`, which separates the URL from the query string. Also, a better way to construct a full URL with query string is to use the `new URL()` object – Terry Aug 18 '21 at 11:53
  • Note that you can't rely on your visitor having a mail client installed and working that `mailto:` can use. I don't have one and `mailto:` links just don't work for me. If you want to be able to send email from a form pass the message to your server and have that send the message. – Tangentially Perpendicular Aug 18 '21 at 12:00

3 Answers3

1

The link have to be like that :

var link = `mailto:${mail}`
           + "?subject=" + encodeURIComponent(`${subject}`)
           + "&body=" + encodeURIComponent(`${body}`);
Elikill58
  • 4,050
  • 24
  • 23
  • 45
1

The query string should be start with ? not &

change &subject to ?subject

it should be //abc@example.com?subject=blahblahblah&body=testtest

Hugo
  • 131
  • 4
0

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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Eklavya Jain
  • 47
  • 10