我希望我的网站有能力发送电子邮件而不刷新页面。我想用Javascript。

<form action="javascript:sendMail();" name="pmForm" id="pmForm" method="post">
Enter Friend's Email:
<input name="pmSubject" id="pmSubject" type="text" maxlength="64" style="width:98%;" />
<input name="pmSubmit" type="submit" value="Invite" />

这是我想调用的函数,但我不确定把什么放入javascript函数。从我所做的研究中,我发现了一个使用mailto方法的示例,但我的理解是,它实际上并不直接从站点发送。

所以我的问题是,我可以在哪里找到什么放入JavaScript函数直接从网站发送电子邮件。

function sendMail() {
    /* ...code here...    */
}

当前回答

另一种从JavaScript发送电子邮件的方法是使用directtomx.com,如下所示;

 Email = {
 Send : function (to,from,subject,body,apikey)
    {
        if (apikey == undefined)
        {
            apikey = Email.apikey;
        }
        var nocache= Math.floor((Math.random() * 1000000) + 1);
        var strUrl = "http://directtomx.azurewebsites.net/mx.asmx/Send?";
        strUrl += "apikey=" + apikey;
        strUrl += "&from=" + from;
        strUrl += "&to=" + to;
        strUrl += "&subject=" + encodeURIComponent(subject);
        strUrl += "&body=" + encodeURIComponent(body);
        strUrl += "&cachebuster=" + nocache;
        Email.addScript(strUrl);
    },
    apikey : "",
    addScript : function(src){
            var s = document.createElement( 'link' );
            s.setAttribute( 'rel', 'stylesheet' );
            s.setAttribute( 'type', 'text/xml' );
            s.setAttribute( 'href', src);
            document.body.appendChild( s );
    }
};

然后从页面中调用它,如下所示;

 window.onload = function(){
    Email.apikey = "-- Your api key ---";
    Email.Send("to@domain.com","from@domain.com","Sent","Worked!");
 }

其他回答

你不能直接用javascript发送电子邮件。

但是,您可以打开用户的邮件客户端:

window.open('mailto:test@example.com');

还有一些参数可以预填充主题和主体:

window.open('mailto:test@example.com?subject=subject&body=body');

另一种解决方案是对服务器进行ajax调用,以便服务器发送电子邮件。注意不要允许任何人通过你的服务器发送任何电子邮件。

window.open (mailto: test@example.com);如上所述 不采取任何措施来隐藏“test@example.com”电子邮件地址,以免被垃圾邮件机器人收集。我以前经常遇到这个问题。

var recipient="test";
var at = String.fromCharCode(64);
var dotcom="example.com";
var mail="mailto:";
window.open(mail+recipient+at+dotcom);

似乎有一个新的解决办法即将出现。它叫EmailJS。他们声称不需要服务器代码。你可以申请邀请。

2016年8月更新:EmailJS似乎已经上线了。你每月可以免费发送200封电子邮件,如果数量更多,还可以订阅。

我要把这个消息告诉你。JavaScript本身不能发送电子邮件。


根据OP问题的上下文,我上面的答案已经不成立了,正如@KennyEvitt在评论中指出的那样。看起来您可以使用JavaScript作为SMTP客户端。

但是,我还没有深入研究它是否足够安全和跨浏览器兼容。所以,我既不鼓励也不劝阻你使用它。使用风险自负。

Javascript是客户端,你不能用Javascript发邮件。浏览器可能只识别mailto:,并启动默认的邮件客户端。