无法使用JavaScript发送电子邮件

时间:2012-06-17 21:17:38

标签: javascript email html-email

Stack Overflow上的旧线程讨论了如何使用JavaScript填写mailto电子邮件:

Sending emails with Javascript

我对应用这项技术很感兴趣,但无法让它发挥作用。

在下面的代码中,当我在makecontact()方法中返回false时设置断点,并查看它记录的URL时,它看起来很好。

但浏览器无法打开电子邮件客户端。

如果我在“提交”按钮的href中对相同的URL进行硬编码,则会启动电子邮件客户端。

为什么不设置href工作?

答案:这是错误的href。

修正版:

<!-- TODO: Validate name and text fields and don't allow submit until they are valid. Limit total mailto URL length to 2000. -->
<form name="contact">
<br/>Reason for contact:
<br/>
<input type="radio" name="reason" value="Product Inquiry/Presales Questions" checked="checked"/>Product Inquiry/Presales Question<br/>
<input type="radio" name="reason" value="Support/Warranty"/>Support/Warranty<br/>
<input type="radio" name="reason" value="Feedback"/>Feedback<br/>
<input type="radio" name="reason" value="Other"/>Other<br/>
<input type="text" name="name" id="name"/>Your name:</div>
<textarea name="contacttext" rows="20" cols="60" id="contacttext"></textarea>
<button id="submit">Submit</button>
</form>
<script type="text/javascript" id="contactjs">

<!--
var submit = document.getElementById("submit");

function getreason() {
    var radios, i, radio;

    radios = document.getElementsByName("reason");

    for (i = 0; i < 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 + "&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;
}
//-->
</script>
</div>

2 个答案:

答案 0 :(得分:3)

    body = "From: ' 
" + name + " 
', Content: ' 
" + text + " 
'"; 

这不是有效的JavaScript。它将导致“未终止的字符串常量”错误。试试这个:

    body = "From: '\n" + name + "\n', Content: '\n" + text + "\n'";

答案 1 :(得分:1)

您有两个主要问题:

  1. button个元素没有href s(HTML4HTML5)。设置一个不会做任何事情。在提交处理程序的末尾,您应该设置document.location.href

    document.location.href = "mailto:contact@analogperfection.com?Subject=" + subject + "&Body=" + body;
    
  2. JavaScript中的字符串中不能包含文字换行符。请改用\n

    body = "From: ' \n" + name + " \n', Content: ' \n" + text + " \n'"; 
    
  3. 还要注意......

    1. 您应该在事件处理程序中接受一个事件对象,并调用event.preventDefault()而不是从事件处理程序返回false,以阻止提交表单。

    2. 没有名为resume的功能,但如果addEventListenerattachEvent都不存在,您就会使用它。