[英]How to send an email from 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" />
這是我想調用該函數的方式,但我不確定將什么放入 javascript 函數中。 從我所做的研究中,我發現了一個使用 mailto 方法的示例,但我的理解是它實際上並不直接從站點發送。
所以我的問題是我在哪里可以找到在 JavaScript 函數中放置的內容以直接從網站發送電子郵件。
function sendMail() {
/* ...code here... */
}
您不能直接使用 javascript 發送電子郵件。
但是,您可以打開用戶的郵件客戶端:
window.open('mailto:test@example.com');
還有一些參數可以預填充主題和正文:
window.open('mailto:test@example.com?subject=subject&body=body');
另一種解決方案是對您的服務器進行 ajax 調用,以便服務器發送電子郵件。 小心不要讓任何人通過您的服務器發送任何電子郵件。
通過您的服務器間接調用 - 調用 3rd Party API - 安全且推薦
您的服務器可以在正確的身份驗證和授權后調用 3rd Party API。 API 密鑰不會向客戶端公開。
node.js - https://www.npmjs.org/package/node-mandrill
const 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){
let _name = req.body.name;
let _email = req.body.email;
let _subject = req.body.subject;
let _messsage = req.body.message;
//implement your spam protection or checks.
sendEmail ( _name, _email, _subject, _message );
});
然后在客戶端使用 $.ajax 調用您的電子郵件 API。
直接從客戶端 - 調用 3rd Party API - 不推薦
簡而言之:
像這樣 -
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 密鑰,因此任何惡意用戶都可能使用您的密鑰發送電子郵件,這可能會耗盡您的配額。
我找不到真正滿足原始問題的答案。
我整理了一個簡單的免費服務,它允許您發出標准的 HTTP POST 請求來發送電子郵件。 它稱為PostMail ,您可以簡單地發布表單,使用 JavaScript 或 jQuery。 當您注冊時,它會為您提供代碼,您可以將這些代碼復制並粘貼到您的網站中。 這里有些例子:
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:
<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>
再次,完全公開,我創建此服務是因為我找不到合適的答案。
我知道我太晚了,無法為這個問題寫答案,但我認為這將適用於任何想通過 javascript 發送電子郵件的人。
我建議的第一種方法是使用回調在服務器上執行此操作。 如果您真的希望使用 javascript 來處理它,那么我建議您這樣做。
我發現的最簡單的方法是使用 smtpJs。 可用於發送電子郵件的免費庫。
1.包含如下腳本
<script src="https://smtpjs.com/v3/smtp.js"></script>
2.您可以發送這樣的電子郵件
Email.send({ Host : "smtp.yourisp.com", Username : "username", Password : "password", To : 'them@website.com', From : "you@isp.com", Subject : "This is the subject", Body : "And this is the body" }).then( message => alert(message) );
這是不可取的,因為它會在客戶端顯示您的密碼。因此,您可以執行以下操作,加密您的 SMTP 憑據,並將其鎖定到單個域,並傳遞安全令牌而不是憑據。
Email.send({ SecureToken : "C973D7AD-F097-4B95-91F4-40ABC5567812", To : 'them@website.com', From : "you@isp.com", Subject : "This is the subject", Body : "And this is the body" }).then( message => alert(message) );
最后,如果您沒有 SMTP 服務器,您可以使用 smtp 中繼服務,例如Elastic Email
此外,這里是SmtpJS.com官方網站的鏈接,您可以在其中找到所需的所有示例以及可以創建安全令牌的位置。
我希望有人覺得這個細節有用。 快樂編碼。
您可以在這篇文章中找到要放入 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 本身發送電子郵件。
根據 OP 問題的上下文,正如@KennyEvitt 在評論中指出的那樣,我上面的回答不再成立。 看起來您可以使用JavaScript 作為 SMTP 客戶端。
但是,我還沒有深入研究它是否足夠安全和跨瀏覽器兼容。 所以,我既不能鼓勵也不能勸阻你使用它。 使用風險自負。
似乎有一個新的解決方案即將出現。 它被稱為EmailJS 。 他們聲稱不需要服務器代碼。 您可以請求邀請。
2016 年 8 月更新:EmailJS 似乎已經上線。 您每月最多可以免費發送 200 封電子郵件,並且它提供更高數量的訂閱。
window.open('mailto:test@example.com'); 如上所述,不會隱藏“test@example.com”電子郵件地址被垃圾郵件機器人收集。 我曾經經常遇到這個問題。
var recipient="test";
var at = String.fromCharCode(64);
var dotcom="example.com";
var mail="mailto:";
window.open(mail+recipient+at+dotcom);
在您的sendMail()
函數中,向后端添加一個 ajax 調用,您可以在其中在服務器端實現它。
我希望我的網站能夠發送電子郵件而不刷新頁面。 所以我想使用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 是客戶端,您不能使用 Javascript 發送電子郵件。 瀏覽器可能只識別mailto:
並啟動您的默認郵件客戶端。
JavaScript 無法從 Web 瀏覽器發送電子郵件。 但是,退出您已經嘗試實施的解決方案,您可以做一些滿足原始要求的事情:
在不刷新頁面的情況下發送電子郵件
您可以使用 JavaScript 構建電子郵件所需的值,然后向實際發送電子郵件的服務器資源發出 AJAX 請求。 (我不知道您使用的是什么服務器端語言/技術,所以這部分取決於您。)
如果您不熟悉 AJAX,快速的 Google 搜索將為您提供大量信息。 通常,您可以使用 jQuery 的 $.ajax() 函數快速啟動並運行它。 您只需要在服務器上有一個可以在請求中調用的頁面。
似乎對此的一個“答案”是實現 SMPT 客戶端。 有關帶有 SMTP 客戶端的 JavaScript 庫,請參閱email.js 。
這是SMTP 客戶端的 GitHub 存儲庫。 基於 repo 的 README,似乎根據客戶端瀏覽器可能需要各種墊片或 polyfill,但總的來說它確實看起來確實可行(如果實際上沒有顯着完成),但即使是合理的,也不容易描述的方式 -長答案在這里。
有組合服務。 您可以將上面列出的解決方案如 mandrill 與服務 EmailJS 結合起來,這可以使系統更加安全。 不過他們還沒有開始服務。
從 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 發送電子郵件,但是有一些方法可以使用 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。
簡短的回答是你不能單獨使用 JavaScript 來做到這一點。 您需要一個服務器端處理程序來連接 SMTP 服務器以實際發送郵件。 網上有很多簡單的郵件腳本,比如PHP的這個:
使用Ajax向 PHP 腳本發送請求,使用 js 檢查必填字段是否不為空或不正確,並記錄由誰從您的服務器發送的郵件。
function sendMail() is good for doing that.
檢查從您的腳本發送郵件時發現的任何錯誤並采取適當的措施。
為了解決它,例如如果郵件地址不正確或由於服務器問題而沒有發送郵件,或者在這種情況下它在隊列中,請立即向用戶報告並防止多次重復發送相同的電子郵件。 使用 jQuery GET 和 POST 從您的腳本中獲取響應
$.get(URL,callback); $.post(URL,callback);
完整的反垃圾郵件版本:
<div class="at">info<i class="fa fa-at"></i>google.com</div>
OR
<div class="at">info@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 或 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.');
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.