我希望我的网站有能力发送电子邮件而不刷新页面。我想用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本身不能发送电子邮件。


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

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

其他回答

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


你的服务器可以调用第三方API。API密钥不会公开给客户端。

node . js

const axios = require('axios');

async function sendEmail(name, email, subject, message) {
  const data = JSON.stringify({
    "Messages": [{
      "From": {"Email": "<YOUR EMAIL>", "Name": "<YOUR NAME>"},
      "To": [{"Email": email, "Name": name}],
      "Subject": subject,
      "TextPart": message
    }]
  });

  const config = {
    method: 'post',
    url: 'https://api.mailjet.com/v3.1/send',
    data: data,
    headers: {'Content-Type': 'application/json'},
    auth: {username: '<API Key>', password: '<Secret Key>'},
  };

  return axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
    });

}

// define your own email api which points to your server.
app.post('/api/sendemail/', function (req, res) {
  const {name, email, subject, message} = req.body;
  //implement your spam protection or checks.
  sendEmail(name, email, subject, message);
});

然后在客户端使用use fetch调用你的电子邮件API。 使用您在Mailjet上注册时使用的电子邮件。您还可以验证更多的地址。Mailjet提供了一个慷慨的免费等级。


2023年更新:正如评论中指出的那样,由于CORS,下面的方法不再有效

只有当您想测试发送电子邮件并执行此操作时,这才有用

访问https://api.mailjet.com/stats(是的,404页面) 并在浏览器控制台中运行这段代码(填充秘密)

直接从客户端-调用第三方API -不推荐


简而言之:

注册Mailjet以获得API密钥和Secret 使用fetch调用API发送电子邮件

像这样——

function sendMail(name, email, subject, message) {
  const myHeaders = new Headers();
  myHeaders.append("Content-Type", "application/json");
  myHeaders.set('Authorization', 'Basic ' + btoa('<API Key>'+":" +'<Secret Key>'));

  const data = JSON.stringify({
    "Messages": [{
      "From": {"Email": "<YOUR EMAIL>", "Name": "<YOUR NAME>"},
      "To": [{"Email": email, "Name": name}],
      "Subject": subject,
      "TextPart": message
    }]
  });

  const requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: data,
  };

  fetch("https://api.mailjet.com/v3.1/send", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));
}

sendMail('Test Name',"<YOUR EMAIL>",'Test Subject','Test Message')

注意:请记住,您的API密钥对任何人都是可见的,因此任何恶意用户都可能使用您的密钥发送电子邮件,从而耗尽您的配额。

完整的反垃圾邮件版本:

<div class="at">info<i class="fa fa-at"></i>google.com</div>
OR
<div class="at">info&#x40;google.com</div>


<style>
.at {
  color: blue;
  cursor: pointer;
}
.at:hover {
  color: red;
}
</style>

<script>
const el33 = document.querySelector(".at");
el33.onclick = () => {
  let recipient="info";
  let at = String.fromCharCode(64);
  let dotcom="google.com";
  let mail="mailto:";
  window.open(mail+recipient+at+dotcom);
}
</script>

你可以在这篇文章中找到在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));
     }
}

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

你的问题没有一个直接的答案,因为我们不能只使用javascript发送电子邮件,但有一些方法可以使用javascript为我们发送电子邮件:

1)使用API并通过javascript调用API为我们发送电子邮件,例如https://www.emailjs.com说你可以在一些设置后使用下面的代码来调用他们的API:

var service_id = 'my_mandrill';
var template_id = 'feedback';
var template_params = {
name: 'John',
reply_email: 'john@doe.com',
message: 'This is awesome!'
};

emailjs.send(service_id,template_id,template_params);

2)创建一个后端代码来为你发送电子邮件,你可以使用任何后端框架来为你做这件事。

3)使用像这样的东西:

window.open('mailto:me@http://stackoverflow.com/');

这将打开你的电子邮件应用程序,这可能会进入阻止弹出在你的浏览器。

一般来说,发送电子邮件是一个服务器任务,所以应该在后端语言中完成,但我们可以使用javascript来收集所需的数据,并将其发送到服务器或api,我们也可以使用第三方应用程序,并通过浏览器使用javascript打开它们。

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

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