如何从 JavaScript 发送电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7381150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send an email from JavaScript
提问by user906357
I want my website to have the ability to send an email without refreshing the page. So I want to use Javascript.
我希望我的网站能够在不刷新页面的情况下发送电子邮件。所以我想使用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" />
Here is how I want to call the function, but I'm not sure what to put into the javascript function. From the research I've done I found an example that uses the mailto method, but my understanding is that doesn't actually send directly from the site.
这是我想要调用该函数的方式,但我不确定该将什么放入 javascript 函数中。从我所做的研究中,我发现了一个使用 mailto 方法的示例,但我的理解是它实际上并没有直接从站点发送。
So my question is where can I find what to put inside the JavaScript function to send an email directly from the website.
所以我的问题是我在哪里可以找到在 JavaScript 函数中放置什么以直接从网站发送电子邮件。
function sendMail() {
/* ...code here... */
}
回答by Arnaud Le Blanc
You can't send an email directly with javascript.
您不能直接使用 javascript 发送电子邮件。
You can, however, open the user's mail client:
但是,您可以打开用户的邮件客户端:
window.open('mailto:[email protected]');
There are also some parameters to pre-fill the subject and the body:
还有一些参数可以预填充主题和正文:
window.open('mailto:[email protected]?subject=subject&body=body');
Another solution would be to do an ajax call to your server, so that the server sends the email. Be careful not to allow anyone to send any email through your server.
另一种解决方案是对您的服务器进行 ajax 调用,以便服务器发送电子邮件。小心不要让任何人通过您的服务器发送任何电子邮件。
回答by rahulroy9202
Indirect via Your Server - Calling 3rd Party API - secure and recommended
通过您的服务器间接调用 - 调用 3rd Party API - 安全且推荐
Your server can call the 3rd Party API after proper authentication and authorization. The API Keys are not exposed to client.
您的服务器可以在正确的身份验证和授权后调用 3rd Party API。API 密钥不会向客户端公开。
node.js- https://www.npmjs.org/package/node-mandrill
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: '[email protected]',
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 );
});
and then use use $.ajax on client to call your email API.
然后在客户端使用 $.ajax 调用您的电子邮件 API。
Directly From Client - Calling 3rd Party API - not recomended
直接从客户端 - 调用 3rd Party API - 不推荐
Send an email using only JavaScript
in short:
1. register for Mandrill to get an API key
2. load jQuery
3. use $.ajax to send an email
Like this -
像这样 -
function sendMail() {
$.ajax({
type: 'POST',
url: 'https://mandrillapp.com/api/1.0/messages/send.json',
data: {
'key': 'YOUR API KEY HERE',
'message': {
'from_email': '[email protected]',
'to': [
{
'email': '[email protected]',
'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
https://medium.com/design-startups/b53319616782
Note: Keep in mind that your API key is visible to anyone, so any malicious user may use your key to send out emails that can eat up your quota.
注意:请记住,任何人都可以看到您的 API 密钥,因此任何恶意用户都可能使用您的密钥发送电子邮件,这可能会耗尽您的配额。
回答by user949286
I couldn't find an answer that really satisfied the original question.
我找不到真正满足原始问题的答案。
- Mandrill is not desirable due to it's new pricing policy, plus it required a backend service if you wanted to keep your credentials safe.
- It's often preferable to hide your email so you don't end up on any lists (the mailto solution exposes this issue, and isn't convenient for most users).
- It's a hassle to set up sendMail or require a backend at all just to send an email.
- Mandrill 是不可取的,因为它是新的定价政策,而且如果你想保证你的凭证安全,它需要一个后端服务。
- 通常最好隐藏您的电子邮件,这样您就不会出现在任何列表中(mailto 解决方案暴露了这个问题,对大多数用户来说并不方便)。
- 设置 sendMail 或仅仅需要一个后端来发送电子邮件都很麻烦。
I put together a simple free service that allows you to make a standard HTTP POST request to send an email. It's called PostMail, and you can simply post a form, use Javascript or jQuery. When you sign up, it provides you with code that you can copy & paste into your website. Here are some examples:
我整理了一个简单的免费服务,它允许您发出标准的 HTTP POST 请求来发送电子邮件。它称为PostMail,您可以简单地发布表单,使用 Javascript 或 jQuery。当您注册时,它会为您提供代码,您可以将这些代码复制并粘贴到您的网站中。这里有些例子:
Javascript:
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>
jQuery:
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>
Again, in full disclosure, I created this service because I could not find a suitable answer.
再次,完全公开,我创建此服务是因为我找不到合适的答案。
回答by Ry-
You can find what to put inside the JavaScript function in this post.
您可以在这篇文章中找到要放入 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));
}
}
Provide your own PHP (or whatever language) script to send the e-mail.
提供您自己的 PHP(或任何语言)脚本来发送电子邮件。
回答by Shef
I am breaking the news to you. You CAN'T send an email with JavaScript per se.
我要告诉你这个消息。你不能用 JavaScript 本身发送电子邮件。
Based on the context of the OP's question, my answer above does not hold true anymore as pointed out by @KennyEvitt in the comments. Looks like you can use JavaScript as an SMTP client.
根据 OP 问题的上下文,正如@KennyEvitt 在评论中指出的那样,我上面的回答不再成立。看起来您可以使用JavaScript 作为 SMTP 客户端。
However, I have not digged deeper to find out if it's secure & cross-browser compatible enough. So, I can neither encourage nor discourage you to use it. Use at your own risk.
但是,我还没有深入研究它是否足够安全和跨浏览器兼容。所以,我既不能鼓励也不能劝阻你使用它。使用风险自负。
回答by Pissu Pusa
I know I am wayyy too late to write an answer for this question but nevertheless I think this will be use for anybody who is thinking of sending emails out via javascript.
我知道我太晚了,无法为这个问题写答案,但我认为这将适用于任何想通过 javascript 发送电子邮件的人。
The first way I would suggest is using a callback to do this on the server. If you really want it to be handled using javascript folowing is what I recommend.
我建议的第一种方法是使用回调在服务器上执行此操作。如果您真的希望使用 javascript 来处理它,那么我建议您这样做。
The easiest way I found was using smtpJs. A free library which can be used to send emails.
我发现的最简单的方法是使用 smtpJs。可用于发送电子邮件的免费库。
1.Include the script like below
1.包含如下脚本
<script src="https://smtpjs.com/v3/smtp.js"></script>
2. You can either send an email like this
2.您可以发送这样的电子邮件
Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"
}).then(
message => alert(message)
);
Which is not advisable as it will display your password on the client side.Thus you can do the following which encrypt your SMTP credentials, and lock it to a single domain, and pass a secure token instead of the credentials instead.
这是不可取的,因为它会在客户端显示您的密码。因此,您可以执行以下操作,加密您的 SMTP 凭据,并将其锁定到单个域,并传递安全令牌而不是凭据。
Email.send({
SecureToken : "C973D7AD-F097-4B95-91F4-40ABC5567812",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"
}).then(
message => alert(message)
);
Finally if you do not have a SMTP server you use an smtp relay service such as Elastic Email
最后,如果您没有 SMTP 服务器,您可以使用 smtp 中继服务,例如Elastic Email
Also here is the link to the official SmtpJS.com websitewhere you can find all the example you need and the place where you can create your secure token.
此外,这里是SmtpJS.com官方网站的链接,您可以在其中找到所需的所有示例以及可以创建安全令牌的位置。
I hope someone find this details useful. Happy coding.
我希望有人觉得这个细节有用。快乐编码。
回答by Christiaan Westerbeek
There seems to be a new solution at the horizon. It's called EmailJS. They claim that no server code is needed. You can request an invitation.
似乎有一个新的解决方案即将出现。它被称为EmailJS。他们声称不需要服务器代码。您可以请求邀请。
Update August 2016: EmailJS seems to be live already. You can send up to 200 emails per month for free and it offers subscriptions for higher volumes.
2016 年 8 月更新:EmailJS 似乎已经上线。您每月最多可以免费发送 200 封电子邮件,并且它提供更高数量的订阅。
回答by greyhound
window.open('mailto:[email protected]'); as above does nothing to hide the "[email protected]" email address from being harvested by spambots. I used to constantly run into this problem.
window.open('mailto:[email protected]'); 如上所述,不会隐藏“[email protected]”电子邮件地址被垃圾邮件机器人收集。我曾经经常遇到这个问题。
var recipient="test";
var at = String.fromCharCode(64);
var dotcom="example.com";
var mail="mailto:";
window.open(mail+recipient+at+dotcom);
回答by evilone
Javascript is client-side, you cannot email with Javascript. Browser recognizes maybe only mailto:
and starts your default mail client.
Javascript 是客户端,您不能使用 Javascript 发送电子邮件。浏览器可能仅识别mailto:
并启动您的默认邮件客户端。
回答by Jeremy Huiskamp
In your sendMail()
function, add an ajax call to your backend, where you can implement this on the server side.
在您的sendMail()
函数中,向后端添加一个 ajax 调用,您可以在其中在服务器端实现它。