通过服务器间接-调用第三方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 );
});
然后在客户端上使用$ .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
像这样 -
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
});
}
https://medium.com/design-startups/b53319616782
注意:请记住,任何人都可以看到您的API密钥,因此任何恶意用户都可以使用您的密钥来发送电子邮件,从而耗尽您的配额。