1

I am trying to send mail using JavaScript when submit button is clicked on the html webpage. Here is my HTML code...

<!DOCTYPE html>
<html>
    <style>
        .heading{
            justify-content: center;
            text-align: center;
        }
    </style>
<body>

   <h2 class="heading">Send e-mail to someone@example.com:</h2>
   <textarea name="myText" id="myText">this is a mail</textarea>
   <button onclick="sendMail(); return false">Send</button>
</body>
</html>

Here is my sendMail function in JavaScript to process the email

 function myFunction(){
  var link="mailto:amarhutiappa@gmail.com"
  + "?cc=mrinal.annand@gmail.com"
  + "&subject=" + encodeURIComponent("This is my subject")
  + "&body="+encodeURIComponent(document.getElementsById('myText')).value
;

window.location.href = link;
}

I can not understand where I am doing wrong! Someone please suggest the right way

Rifky Niyas
  • 1,737
  • 10
  • 25
Mrinal Anand
  • 65
  • 1
  • 11

1 Answers1

1

Edit - Send an email directly via JavaScript

If you are looking to send an email without using html mailto: there is a library called smtpJS. View a simplified tutorial here.

BUT I WOULD NOT SUGGEST TO USE YOUR PERSONAL EMAIL HERE

In your case you can use it like below

const sendMail = (e) => {
    e.preventDefault()
    const message = encodeURIComponent(document.getElementById('message').value)
    Email.send({
        Host : "smtp.yourisp.com",
        Username : "username",
        Password : "password",
        To : 'them@website.com',
        From : "you@isp.com",
        Subject : encodeURIComponent("This is my subject"),
        Body : message
    }).then(
      message => alert(message)
    ).catch( err => {
        alert(err)
    });
}
<!DOCTYPE html>
<html lang="en">
<body>
    <form method="post" onsubmit="sendMail(event)">
        <textarea name="message" id="message">Sample Text</textarea>
        <button type="submit">Send Email</button>
    </form>
    <script src="https://smtpjs.com/v3/smtp.js"></script>
</body>
</html>

You can setup your configuration as per your credentials. If you are using Gmail you can use the credentials mentioned in this article

Disclaimer

I did not test it out completely since I was reluctant to use my personal mail address and I do not have a mail address for production. Please do further research and edit this answer post if necessary

Old Answer

There were some errors in your code and here is the fixed code...

const sendMail = () => {
  const mailAdress = "someone@example.com"
  const ccRecipients =  "mrinal.annand@gmail.com"
  const subject = encodeURIComponent("This is my subject")
  const body = encodeURIComponent(document.getElementById('myText').value)
  const  link= `mailto:${mailAdress}?cc=${ccRecipients}&subject=${subject}&body=${body}`
  window.location.href = link;
}
<!DOCTYPE html>
<html>
    <style>
        .heading{
            justify-content: center;
            text-align: center;
        }
    </style>
<body>

   <h2 class="heading">Send e-mail to someone@example.com:</h2>
   <textarea name="myText" id="myText">this is a mail</textarea>
   <button onclick="sendMail()">Send</button>
</body>
</html>

First of all you haven't defined the function sendMail() in your JavaScript code and instead defined myFunction().

Second it's better to assign the mail address, cc recipients, subject and body as variables since they can be made dynamic or to easily change the hardcoded values. Next you can concatenate the variables using ES6 Template Literals to have in ease in reading and writing the code.

Thirdly, the below code is incorrect.

 encodeURIComponent(document.getElementsById('myText')).value

You should pass the value of text area to the encodeURIComponent() function. For that first you must get the value in text area by document.getElementsById('myText').value and pass that value into encodeURIComponent(). The corrected code will look like this

encodeURIComponent(document.getElementById('myText').value)

Also if you want to understand the use of HTML mailto, refer this article

Rifky Niyas
  • 1,737
  • 10
  • 25
  • @Mrinal Anand Using `const` is a better approach to define the functions and the variables in JavaScript ES6. Specially here I used it to make the function immutable. So you don't have to worry about function being changed by other parts of code. Refer more in [this answer](https://stackoverflow.com/a/42803030/13833218) – Rifky Niyas Aug 04 '21 at 03:23
  • yeah, that was a mistake, i mean that myFucntion() call , what i was trying to do is to send a mail from mrinal.annand@gmail.com to amarhutiappa@gmail.com when submit button is clicked....what else is needed – Mrinal Anand Aug 04 '21 at 03:25
  • I'll add some further explanation to the answer. I have corrected the errors in your code and given the corrected snippet. Does it work? – Rifky Niyas Aug 04 '21 at 03:28
  • i changed ccRecipient to amarhutiappa@gmail.com and mailAdress to mrinal.annand@gmail.com, but it doesn't work – Mrinal Anand Aug 04 '21 at 03:31
  • Can you explain on how it does not work? Do you mean that email is not being sent? – Rifky Niyas Aug 04 '21 at 03:33
  • yes, the email is not being sent, i included the js file in the html file using script tag – Mrinal Anand Aug 04 '21 at 03:36
  • To be clear, after including the above corrected snippet your default email application opens up with the correct data right? – Rifky Niyas Aug 04 '21 at 03:38
  • @MrinalAnand Remember that `mailAdress` means the mail address to which the message is sent to. If the email address you are using in your default email application is same as the address to which the mail is sent, it won't work. In your case. In your case if your email is _mrinal.annand@gmail.com_ and you are trying to send an email to the same address it won't work – Rifky Niyas Aug 04 '21 at 03:49
  • @MrinalAnand assuming that you are using gmail here is an example. Suppose you have logged on to your account using _sender@gmail.com_ Then you can send an email to _reciever@gmail.com_ and add a Cc recipient to _anotherreceiver@gmail.com_. But you can not send an email to _sender@gmail.com_. Did you understand? – Rifky Niyas Aug 04 '21 at 04:30
  • here i am logged in to mrinal.annand@gmail.com and sending to ama...@gmail.com. and i have removed that Ccrecipient, now it should work,right? – Mrinal Anand Aug 04 '21 at 04:51
  • yes. If it's not working, do you get any error messages? If so what are they? – Rifky Niyas Aug 04 '21 at 05:12
  • OK. Does the code opens up the default email service with the added details? – Rifky Niyas Aug 04 '21 at 05:16
  • i am using Gmail as the email service, if you mean that on clicking submit button whether Gmail is opening or not , then answer is no – Mrinal Anand Aug 04 '21 at 05:21
  • i hope i got your point "with added details". if not, let me know what you mean by that – Mrinal Anand Aug 04 '21 at 05:22
  • mm ok. Can you just elaborate what happens when you click the send button? – Rifky Niyas Aug 04 '21 at 14:08
  • i read somewhere that it is not possible to send mail using pure javascript only, am i doing right? although answering your qstn -->nothing happens clicking on send button, even the console is empty before and after clicking – Mrinal Anand Aug 04 '21 at 15:33
  • You can not mail a person via vanilla JavaScript but what you are trying above is to send an email by opening the default email application of the user. And I have provided a working solution for that above. I am not quite sure why nothing happens when you click the send button. Did you actually copy the code I have added in my answer? Did you try running the snippet actually? It works fine here... – Rifky Niyas Aug 04 '21 at 15:37
  • yes, first i did copy paste the code given by you, updated the email addresses ( i mean someone@example.com to amar....@gmail.com ) and tried ...it didn't work,... included the javascript file in html file,...didn't work,....excluded Ccrecipient address,...didn't work....moved to sending mail using nodejs – Mrinal Anand Aug 04 '21 at 15:57
  • are you able to send mails through this code only, on your computer? – Mrinal Anand Aug 04 '21 at 16:00
  • my issue hasn't been solved yet!!! how can i upvote? – Mrinal Anand Aug 04 '21 at 16:04
  • I am asking you to upvote if my answer gives a solution only!! And remember my original answer has already answered what you have asked! – Rifky Niyas Aug 04 '21 at 16:22
  • i did upvote as you have put in a lot of time and energy for my issue and i am very thankful for all those.. – Mrinal Anand Aug 04 '21 at 19:36
  • @MrinalAnand It seems like I did not receive upvote yet. This answer gives the solution to your question and has corrected the error in your code that you have submitted. Please upvote the answer and accept it if it solves your problem – Rifky Niyas Aug 15 '21 at 07:05