JavaScript에서 이메일을 보내는 방법
페이지를 갱신하지 않고 메일을 송신할 수 있는 기능을 Web 사이트에 가지고 싶다.그래서 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" />
함수는 이렇게 부르고 싶은데 자바스크립트 함수에 무엇을 넣어야 할지 모르겠어요.제가 조사한 결과, mailto 방식을 사용한 예는 발견되었지만, 실제로는 사이트에서 직접 송신하지 않는 것으로 알고 있습니다.
그래서 제 질문은 웹 사이트에서 직접 이메일을 보내기 위해 자바스크립트 기능에 무엇을 넣어야 하는지입니다.
function sendMail() {
/* ...code here... */
}
javascript로는 메일을 직접 보낼 수 없습니다.
그러나 사용자의 메일 클라이언트를 열 수 있습니다.
window.open('mailto:test@example.com');
제목과 본문을 미리 채우기 위한 매개 변수도 몇 가지 있습니다.
window.open('mailto:test@example.com?subject=subject&body=body');
또 다른 해결책은 서버에 Ajax 콜을 실행하여 서버가 이메일을 보내는 것입니다.다른 사용자가 서버를 통해 이메일을 보낼 수 없도록 주의하십시오.
서버를 통한 간접 - 서드파티 API 호출 - 안전하고 권장
서버는 서드파티 API를 호출할 수 있습니다.API 키는 클라이언트에 노출되지 않습니다.
node.displaces(node.
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);
});
그런 다음 클라이언트 측에서 fetch를 사용하여 이메일 API를 호출합니다.from email메일젯에 등록하셨던 파일입니다.더 많은 주소를 인증할 수도 있습니다.메일젯은 넉넉한 프리티어를 제공합니다.
클라이언트에서 직접 - 서드파티 API 호출 - 권장 안 함
요컨대:
- API 키와 Secret을 얻기 위해 Mailjet에 등록합니다.
- 가져오기 기능을 사용하여 API를 호출하여 이메일 보내기
이렇게...
function sendMail(name, email, subject, message) {
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.set('Authorization', 'Basic ' + base64.encode('<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));
}
주의: 사용자의 API 키는 누구나 볼 수 있으므로 악의적인 사용자가 사용자의 키를 사용하여 할당량을 잠식할 수 있는 이메일을 보낼 수 있습니다.
나는 원래의 질문에 정말 맞는 답을 찾을 수 없었다.
- Mandrill은 새로운 가격 정책 때문에 바람직하지 않으며 자격 증명을 안전하게 유지하려면 백엔드 서비스가 필요합니다.
- e-메일을 숨김으로써 목록에 표시되지 않도록 하는 것이 좋습니다(mailto 솔루션은 이 문제를 노출하므로 대부분의 사용자에게 편리하지 않습니다).
- send Mail을 설정하거나 이메일을 보내는 데만 백엔드가 필요합니다.
저는 당신이 표준 HTTP POST 요청을 하고 이메일을 보낼 수 있는 간단한 무료 서비스를 준비했습니다.이것은 Post Mail이라고 불리며 단순히 폼을 게시하거나 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>
j쿼리:
<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 folling을 사용하여 처리하길 원하신다면 추천드립니다.
가장 쉬운 방법은 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 credential을 암호화하여 단일 도메인에 잠근 후 credential 대신 안전한 토큰을 전달할 수 있습니다.
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 서버가 없는 경우 Elastic Email 등의 SMTP 릴레이 서비스를 사용합니다.
또한 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월 갱신: 이메일JS는 이미 생방송인 것 같아요.매월 최대 200개의 전자 메일을 무료로 보낼 수 있으며 더 많은 볼륨을 구독할 수 있습니다.
window.open submailto: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()아약스서버측에서 이 콜을 실장할 수 있습니다.
자바스크립트할 수 있는 은 「」뿐입니다.mailto:기본 메일 클라이언트를 시작합니다.
JavaScript가 웹 브라우저에서 이메일을 보낼 수 없습니다.다만, 이미 실장하고 있던 솔루션으로부터 한 발 물러서, 원래의 요건을 만족시키는 작업을 실시할 수 있습니다.
페이지를 갱신하지 않고 이메일을 송신하다
JavaScript를 사용하여 이메일에 필요한 값을 구성한 후 실제로 이메일을 보내는 서버 리소스에 AJAX 요청을 할 수 있습니다.(어떤 서버측 언어/테크놀로지를 사용하고 있는지 알 수 없기 때문에, 그 부분은 고객에게 달려 있습니다.)
AJAX에 익숙하지 않은 경우 Google에서 빠르게 검색하면 많은 정보를 얻을 수 있습니다.일반적으로 jQuery의 $.ajax() 함수를 사용하면 빠르게 실행할 수 있습니다.서버에서 요청으로 호출할 수 있는 페이지만 있으면 됩니다.
이에 대한 하나의 '답안'은 SMPT 클라이언트를 구현하는 것입니다.SMTP 클라이언트를 사용하는 JavaScript 라이브러리에 대해서는, email.js 를 참조해 주세요.
여기 SMTP 클라이언트의 GitHub repo가 있습니다.Repo의 README에 따르면 클라이언트브라우저에 따라서는 다양한 심이나 폴리필이 필요할 수 있다고 생각되지만, 전체적으로 (실제로 큰 성과를 거두지 못한 경우라도) 실현 가능성이 있는 것 같습니다.여기서는 상당히 긴 답변으로도 쉽게 설명할 수 있는 방법이 아닙니다.
콤비네이션 서비스가 있습니다.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를 사용하여 브라우저로 열 수도 있습니다.
만약, 그리고 만약 내가 그것을 사용해야 한다면,somejs library, SMTPJs 라이브러리에서는 그렇게 할 수 있습니다.사용자 이름, 비밀번호 등의 자격 정보를 암호화합니다.
간단히 말하면 JavaScript만으로는 할 수 없습니다.실제로 메일을 발송하려면 SMTP 서버에 연결하려면 서버측 처리기가 필요합니다.온라인에는 다음과 같은 간단한 메일 스크립트가 많이 있습니다.
Ajax를 사용하여 PHP 스크립트로 요청을 전송합니다.js를 사용하여 필수 필드가 비어 있지 않거나 올바르지 않은지 확인합니다.또, 서버로부터 송신된 메일의 기록도 보관합니다.
function sendMail() is good for doing that.
스크립트에서 메일을 보내는 동안 오류가 발견되었는지 확인하고 적절한 조치를 취하십시오.
예를 들어 메일 주소가 잘못되었거나 서버 문제로 메일이 발송되지 않거나 대기열에 있을 경우 즉시 사용자에게 보고하여 동일한 메일을 여러 번 보내는 것을 방지합니다.jQuery GET 및 POST를 사용하여 스크립트에서 응답을 얻습니다.
$.get(URL, 콜백), $.post(URL, 콜백);
모두 훌륭한 정보이기 때문에 Javascript에서 메일을 보낼 수 있는 Mandrill이라는 작은 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.');
}
}
}
언급URL : https://stackoverflow.com/questions/7381150/how-to-send-an-email-from-javascript
'programing' 카테고리의 다른 글
| 전체 MySQL 데이터베이스에 대한 모든 외부 키 제약 조건 보기 (0) | 2022.11.14 |
|---|---|
| Java를 사용하여 16진수 덤프의 문자열 표현을 바이트 배열로 변환하시겠습니까? (0) | 2022.11.14 |
| javascript에서 포커스를 지우려면 어떻게 해야 하나요? (0) | 2022.11.14 |
| 텍스트 입력 필드에서 Enter 키를 검출합니다. (0) | 2022.11.14 |
| PHP var_dump()와 같이 Smarty에서 변수를 디버깅하는 방법 (0) | 2022.11.14 |