如何从JavaScript发送电子邮件

use*_*357 217 javascript email

我希望我的网站能够在不刷新页面的情况下发送电子邮件.所以我想使用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" />
Run Code Online (Sandbox Code Playgroud)

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

所以我的问题是我在哪里可以找到JavaScript函数中的内容,直接从网站发送电子邮件.

function sendMail() {
    /* ...code here...    */
}
Run Code Online (Sandbox Code Playgroud)

Arn*_*anc 287

您无法使用javascript直接发送电子邮件.

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

window.open('mailto:test@example.com');
Run Code Online (Sandbox Code Playgroud)

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

window.open('mailto:test@example.com?subject=subject&body=body');
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是对服务器进行ajax调用,以便服务器发送电子邮件.小心不要让任何人通过您的服务器发送任何电子邮件.

  • 只需注意,您也可以使用`window.location.href`(如此答案:http://stackoverflow.com/questions/271171/sending-emails-with-javascript/271172#271172)打开电子邮件客户端当用户完成电子邮件时,它不会留下那个空窗口. (11认同)
  • 我会更进一步并执行 `window.open( String( 'mailto:recipient^example.com' ).replace('^', '@') );` 来混淆垃圾邮件机器人 (7认同)
  • 答案确实没有回答问题,但@ rahulroy的回答很好 (3认同)
  • 如果打开页面的程序已经具有电子邮件客户端功能..(如Opera 12.50)那么,它将打开链接作为常规URL.他们也是具有firefox gecko引擎的Thunderbird:它可以从电子邮件中的超链接打开网页作为新标签. (2认同)
  • “主题”和“正文”是变量还是字段中的实际文本? (2认同)

rah*_*202 88

间接通过您的服务器 - 调用第三方API - 安全和推荐


经过适当的身份验证和授权后,您的服务器可以调用第三方API.API密钥不会向客户端公开.

node.js - https://www.npmjs.org/package/node-mandrill

var mandrill = require('node-mandrill')('<your API Key>'); 

function sendEmail ( _name, _email, _subject, _message) {
    mandrill('/messages/send', {
        message: {
            to: [{email: _email , name: _name}],
            from_email: 'noreply@yourdomain.com',
            subject: _subject,
            text: _message
        }
    }, function(error, response){
        if (error) console.log( error );
        else console.log(response);
    });
}

// define your own email api which points to your server.

app.post( '/api/sendemail/', function(req, res){

    var _name = req.body.name;
    var _email = req.body.email;
    var _subject = req.body.subject;
    var _messsage = req.body.message;

    //implement your spam protection or checks. 

    sendEmail ( _name, _email, _subject, _message );

});
Run Code Online (Sandbox Code Playgroud)

然后使用$ .ajax在客户端上调用您的电子邮件API.


直接来自客户 - 调用第三方API - 不推荐


仅使用JavaScript发送电子邮件

in short: 
1. register for Mandrill to get an API key
2. load jQuery
3. use $.ajax to send an email
Run Code Online (Sandbox Code Playgroud)

像这样 -

function sendMail() {
    $.ajax({
      type: 'POST',
      url: 'https://mandrillapp.com/api/1.0/messages/send.json',
      data: {
        'key': 'YOUR API KEY HERE',
        'message': {
          'from_email': 'YOUR@EMAIL.HERE',
          'to': [
              {
                'email': 'RECIPIENT@EMAIL.HERE',
                'name': 'RECIPIENT NAME (OPTIONAL)',
                'type': 'to'
              }
            ],
          'autotext': 'true',
          'subject': 'YOUR SUBJECT HERE!',
          'html': 'YOUR EMAIL CONTENT HERE! YOU CAN USE HTML!'
        }
      }
     }).done(function(response) {
       console.log(response); // if you're into that sorta thing
     });
}
Run Code Online (Sandbox Code Playgroud)

https://medium.com/design-startups/b53319616782

注意:请注意,任何人都可以看到您的API密钥,因此任何恶意用户都可能使用您的密钥发送可能会占用您配额的电子邮件.

  • 尽管文章确实说过这个我觉得应该在这里说,即使这会起作用,但是还有一些安全问题,因为你需要将api密钥发送给客户端.这可能会被滥用. (7认同)

use*_*286 31

我找不到真正满足原始问题的答案.

  • Mandrill因其新的定价政策而不可取,如果您想保证您的凭证安全,则需要后端服务.
  • 通常最好隐藏您的电子邮件,这样您就不会在任何列表上结束(mailto解决方案会暴露此问题,对大多数用户来说并不方便).
  • 设置sendMail或者根本需要后端来发送电子邮件是一件麻烦事.

我整理了一个简单的免费服务,允许您发出标准的HTTP POST请求来发送电子邮件.它被称为PostMail,你可以简单地发布一个表单,使用Javascript或jQuery.当您注册时,它会为您提供可以复制并粘贴到您网站的代码.这里有些例子:

使用Javascript:

<form id="javascript_form">
    <input type="text" name="subject" placeholder="Subject" />
    <textarea name="text" placeholder="Message"></textarea>
    <input type="submit" id="js_send" value="Send" />
</form>

<script>

    //update this with your js_form selector
    var form_id_js = "javascript_form";

    var data_js = {
        "access_token": "{your access token}" // sent after you sign up
    };

    function js_onSuccess() {
        // remove this to avoid redirect
        window.location = window.location.pathname + "?message=Email+Successfully+Sent%21&isError=0";
    }

    function js_onError(error) {
        // remove this to avoid redirect
        window.location = window.location.pathname + "?message=Email+could+not+be+sent.&isError=1";
    }

    var sendButton = document.getElementById("js_send");

    function js_send() {
        sendButton.value='Sending…';
        sendButton.disabled=true;
        var request = new XMLHttpRequest();
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                js_onSuccess();
            } else
            if(request.readyState == 4) {
                js_onError(request.response);
            }
        };

        var subject = document.querySelector("#" + form_id_js + " [name='subject']").value;
        var message = document.querySelector("#" + form_id_js + " [name='text']").value;
        data_js['subject'] = subject;
        data_js['text'] = message;
        var params = toParams(data_js);

        request.open("POST", "https://postmail.invotes.com/send", true);
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        request.send(params);

        return false;
    }

    sendButton.onclick = js_send;

    function toParams(data_js) {
        var form_data = [];
        for ( var key in data_js ) {
            form_data.push(encodeURIComponent(key) + "=" + encodeURIComponent(data_js[key]));
        }

        return form_data.join("&");
    }

    var js_form = document.getElementById(form_id_js);
    js_form.addEventListener("submit", function (e) {
        e.preventDefault();
    });
</script>
Run Code Online (Sandbox Code Playgroud)

jQuery的:

<form id="jquery_form">
    <input type="text" name="subject" placeholder="Subject" />
    <textarea name="text" placeholder="Message" ></textarea>
    <input type="submit" name="send" value="Send" />
</form>

<script>

    //update this with your $form selector
    var form_id = "jquery_form";

    var data = {
        "access_token": "{your access token}" // sent after you sign up
    };

    function onSuccess() {
        // remove this to avoid redirect
        window.location = window.location.pathname + "?message=Email+Successfully+Sent%21&isError=0";
    }

    function onError(error) {
        // remove this to avoid redirect
        window.location = window.location.pathname + "?message=Email+could+not+be+sent.&isError=1";
    }

    var sendButton = $("#" + form_id + " [name='send']");

    function send() {
        sendButton.val('Sending…');
        sendButton.prop('disabled',true);

        var subject = $("#" + form_id + " [name='subject']").val();
        var message = $("#" + form_id + " [name='text']").val();
        data['subject'] = subject;
        data['text'] = message;

        $.post('https://postmail.invotes.com/send',
            data,
            onSuccess
        ).fail(onError);

        return false;
    }

    sendButton.on('click', send);

    var $form = $("#" + form_id);
    $form.submit(function( event ) {
        event.preventDefault();
    });
</script>
Run Code Online (Sandbox Code Playgroud)

再次,在完全披露中,我创建了这项服务,因为我找不到合适的答案.

  • 这与其他人有同样的问题吗?访问令牌(API密钥)被公开 (3认同)
  • 这是最好的解决方案。非常感谢。Mandrill 不再有免费计划,并且 mailgun 不支持 cors,因此不支持 JavaScript (2认同)
  • 他们每天限制为 25 封电子邮件。 (2认同)

Ry-*_*Ry- 25

您可以在本文中找到JavaScript函数中的内容.

function getAjax() {
    try {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try {
                return new ActiveXObject('Msxml2.XMLHTTP');
            } catch (try_again) {
                return new ActiveXObject('Microsoft.XMLHTTP');
            }
        }
    } catch (fail) {
        return null;
    }
}

function sendMail(to, subject) {
     var rq = getAjax();

     if (rq) {
         // Success; attempt to use an Ajax request to a PHP script to send the e-mail
         try {
             rq.open('GET', 'sendmail.php?to=' + encodeURIComponent(to) + '&subject=' + encodeURIComponent(subject) + '&d=' + new Date().getTime().toString(), true);

             rq.onreadystatechange = function () {
                 if (this.readyState === 4) {
                     if (this.status >= 400) {
                         // The request failed; fall back to e-mail client
                         window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
                     }
                 }
             };

             rq.send(null);
         } catch (fail) {
             // Failed to open the request; fall back to e-mail client
             window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
         }
     } else {
         // Failed to create the request; fall back to e-mail client
         window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
     }
}
Run Code Online (Sandbox Code Playgroud)

提供您自己的PHP(或任何语言)脚本来发送电子邮件.


She*_*hef 18

我正在向你发消息.您无法发送包含JavaScript的电子邮件.


根据OP问题的背景,正如@KennyEvitt在评论中指出的那样,我上面的答案不再适用.看起来您可以使用JavaScript作为SMTP客户端.

但是,我没有深入挖掘,以确定它是否足够安全和​​跨浏览器兼容.所以,我既不鼓励也不鼓励你使用它.使用风险由您自己承担.


Chr*_*eek 7

似乎有一种新的解决方案.它叫做EmailJS.他们声称不需要服务器代码.您可以申请邀请.

2016年8月更新:EmailJS似乎已经上线.您每月最多可以免费发送200封电子邮件,并提供更高容量的订阅.

  • 这很晚了,但@MagedSaeed 在电子邮件模板部分,编辑模板时,您可以指定“收件人”电子邮件。您甚至可以使用他们的模板选项使“收件人”字段动态化。他们的文档做得很好,详细说明了它。 (2认同)

小智 6

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);
Run Code Online (Sandbox Code Playgroud)


Pis*_*usa 6

我知道我现在还没来得及写这个问题的答案,但是我认为这将对那些想通过javascript发送电子邮件的人有用。

我建议的第一种方法是使用回调在服务器上执行此操作。如果您真的希望使用javascript进行处理,那么我建议您这样做。

我发现最简单的方法是使用smtpJs。一个免费的库,可用于发送电子邮件。

1.包括如下脚本

<script src="https://smtpjs.com/v3/smtp.js"></script>
Run Code Online (Sandbox Code Playgroud)

2.您可以发送这样的电子邮件

<script src="https://smtpjs.com/v3/smtp.js"></script>
Run Code Online (Sandbox Code Playgroud)

不建议这样做,因为它将在客户端显示密码。因此,您可以执行以下操作来加密SMTP凭据,并将其锁定到单个域,然后传递安全令牌代替凭据。

Email.send({
    Host : "smtp.yourisp.com",
    Username : "username",
    Password : "password",
    To : 'them@website.com',
    From : "you@isp.com",
    Subject : "This is the subject",
    Body : "And this is the body"
    }).then(
      message => alert(message)
    );
Run Code Online (Sandbox Code Playgroud)

最后,如果您没有SMTP服务器,请使用smtp中继服务,例如Elastic Email

另外,这里还有指向SmtpJS.com官方网站的链接,您可以在其中找到所需的所有示例以及可以创建安全令牌的位置。

我希望有人觉得这个细节有用。快乐的编码。

  • @smoore4 是的,但他们仍然必须在他们的服务器上解密它,并且他们可以访问你的密码和东西。我不会相信这项服务。 (4认同)
  • 这仍然使第三方可以完全访问您的SMTP服务器,以便他们可以为您中继邮件以换取……什么? (3认同)
  • 错误“未捕获的引用错误:电子邮件未定义”是预期的吗?我很确定您没有定义“电子邮件”。或者您是否使用了代码片段而不仅仅是代码围栏,并且我们不应该运行它?而且我认为你还不算太晚。 (2认同)

Jer*_*amp 5

在您的sendMail()函数中,向后端添加ajax调用,您可以在服务器端实现此操作.