title: Unable To Send Emails With JavaScript
body: <p>An old thread on Stack Overflow discusses how to use JavaScript to fill in a mailto email:</p>
  
  <p><a href="https://stackoverflow.com/questions/271171/sending-emails-with-javascript">Sending emails with Javascript</a></p>
  
  <p>I was interested in applying the technique, but couldn't get it to work.</p>
  
  <p>In the code below, when I set a breakpoint on return false in the makecontact() method, and look at the URL that it logs, it looks fine.</p>
  
  <p>But the browser does not open the email client.</p>
  
  <p>If I hardcode the same URL in an href in the Submit button, then it launches the email client.</p>
  
  <p>Why doesn't setting the href work?</p>
  
  <p>ANSWER: It was the wrong href.</p>
  
  <p>Fixed version:</p>
  
  <pre><code>&lt;!-- TODO: Validate name and text fields and don't allow submit until they are valid. Limit total mailto URL length to 2000. --&gt;
  &lt;form name="contact"&gt;
  &lt;br/&gt;Reason for contact:
  &lt;br/&gt;
  &lt;input type="radio" name="reason" value="Product Inquiry/Presales Questions" checked="checked"/&gt;Product Inquiry/Presales Question&lt;br/&gt;
  &lt;input type="radio" name="reason" value="Support/Warranty"/&gt;Support/Warranty&lt;br/&gt;
  &lt;input type="radio" name="reason" value="Feedback"/&gt;Feedback&lt;br/&gt;
  &lt;input type="radio" name="reason" value="Other"/&gt;Other&lt;br/&gt;
  &lt;input type="text" name="name" id="name"/&gt;Your name:&lt;/div&gt;
  &lt;textarea name="contacttext" rows="20" cols="60" id="contacttext"&gt;&lt;/textarea&gt;
  &lt;button id="submit"&gt;Submit&lt;/button&gt;
  &lt;/form&gt;
  &lt;script type="text/javascript" id="contactjs"&gt;
  
  &lt;!--
  var submit = document.getElementById("submit");
  
  function getreason() {
      var radios, i, radio;
  
      radios = document.getElementsByName("reason");
  
      for (i = 0; i &lt; radios.length; i += 1) {
          radio = radios[i];
          if (radio.checked) {
              break;
          }
      }
  
      return encodeURIComponent(radio.value);
  }
  
  function makecontact(e) {
      var subject, name, text;
  
      subject = getreason();
      name = document.getElementById("name").value;
      text = document.getElementById("contacttext").value;
      body = "From: '" + name + "', Content: '" + text + "'";
      body = encodeURIComponent(body);
  
      document.location.href = "mailto:contact@analogperfection.com?Subject=" + subject + "&amp;Body=" + body;
      console.log(document.location.href);
  
      e.preventDefault();
  
      return false;
  }
  
  if (submit.addEventListener) {
      submit.addEventListener("click", makecontact, true);
  } else if (form.attachEvent) {
      submit.attachEvent("onclick", makecontact);
  } else {
      submit.click = makecontact;
  }
  //--&gt;
  &lt;/script&gt;
  &lt;/div&gt;
  </code></pre>