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

当前回答

间接通过您的服务器-调用第三方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密钥对任何人都是可见的,因此任何恶意用户都可能使用您的密钥发送电子邮件,从而耗尽您的配额。

其他回答

使用JavaScript或jQuery发送邮件

var ConvertedFileStream;
var g_recipient;
var g_subject;
var g_body;
var g_attachmentname;


function SendMailItem(p_recipient, p_subject, p_body, p_file, p_attachmentname, progressSymbol) {

    // Email address of the recipient 
    g_recipient = p_recipient;

   // Subject line of an email
    g_subject = p_subject;

   // Body description of an email
    g_body = p_body;

    // attachments of an email
    g_attachmentname = p_attachmentname;

    SendC360Email(g_recipient, g_subject, g_body, g_attachmentname);

}

function SendC360Email(g_recipient, g_subject, g_body, g_attachmentname) {
    var flag = confirm('Would you like continue with email');
    if (flag == true) {

        try {
            //p_file = g_attachmentname;
            //var FileExtension = p_file.substring(p_file.lastIndexOf(".") + 1);
           // FileExtension = FileExtension.toUpperCase();
            //alert(FileExtension);
            SendMailHere = true;

            //if (FileExtension != "PDF") {

            //    if (confirm('Convert to PDF?')) {
            //        SendMailHere = false;                    
            //    }

            //}
            if (SendMailHere) {
                var objO = new ActiveXObject('Outlook.Application');

                var objNS = objO.GetNameSpace('MAPI');

                var mItm = objO.CreateItem(0);

                if (g_recipient.length > 0) {
                    mItm.To = g_recipient;
                }

                mItm.Subject = g_subject;

                // if there is only one attachment                 
                // p_file = g_attachmentname;
                // mAts.add(p_file, 1, g_body.length + 1, g_attachmentname);

                // If there are multiple attachment files
                //Split the  files names
                var arrFileName = g_attachmentname.split(";");
                 // alert(g_attachmentname);
                //alert(arrFileName.length);
                var mAts = mItm.Attachments;

                for (var i = 0; i < arrFileName.length; i++)
                {
                    //alert(arrFileName[i]);
                    p_file = arrFileName[i];
                    if (p_file.length > 0)
                    {                     
                        //mAts.add(p_file, 1, g_body.length + 1, g_attachmentname);
                        mAts.add(p_file, i, g_body.length + 1, p_file);

                    }
                }

                mItm.Display();

                mItm.Body = g_body;

                mItm.GetInspector.WindowState = 2;

            }
            //hideProgressDiv();

        } catch (e) {
            //debugger;
            //hideProgressDiv();
            alert('Unable to send email.  Please check the following: \n' +
                    '1. Microsoft Outlook is installed.\n' +
                    '2. In IE the SharePoint Site is trusted.\n' +
                    '3. In IE the setting for Initialize and Script ActiveX controls not marked as safe is Enabled in the Trusted zone.');
        }
    }
  }

另一种从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本身不能发送电子邮件。


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

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

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

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

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

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

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

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

间接通过您的服务器-调用第三方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密钥对任何人都是可见的,因此任何恶意用户都可能使用您的密钥发送电子邮件,从而耗尽您的配额。