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