https://github.com/PHPMailer/PHPMailer
PHPMailer/PHPMailer
The classic email sending library for PHP. Contribute to PHPMailer/PHPMailer development by creating an account on GitHub.
github.com
1월 19일 기준 최신버전 적용
회사 소개페이지에 문의하기를 이메일전송으로 구현해봄
문의하기 버튼을 누르면 자바스크립트에서 함수가 실행, php파일을 불러오도록 구현
제가 만든 홈페이지는
https://www.free-css.com/free-css-templates/page256/newbiz 여기 템플릿을 수정한 것인데,
거기에 있는 contact.js 파일을 수정했습니다.
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function () {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
console.log(i);
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
console.log(rule);
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
console.log(i.is(':checked'));
// if (! i.checked) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
// i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
i.siblings('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var action = $(this).attr('action');
if (!action) {
action = '/forms/mailer.php';
}
var r = confirm('메일을 전송하시겠습니까?');
if (r == true) {
$.ajax({
type: "POST",
url: action,
data: str
// data: formData,
//data: $(form).serialize(),
// success: function(msg) {
// alert(msg);
// if (msg == 'OK') {
// $("#sendmessage").addClass("show");
// $("#errormessage").removeClass("show");
// $('.contactForm').find("input, textarea").val("");
// } else {
// $("#sendmessage").removeClass("show");
// $("#errormessage").addClass("show");
// $('#errormessage').html(msg);
// }
// }
}).done(function (data) {
var msg = "문의 메일이 전송되었습니다.\r\nYour contact email has been sent.";
console.log(data);
alert(msg);
}).fail(function() {
var msg = "메일 발송에 실패했습니다.\r\nSoemthing went wrong. Cannot send E-mail.;
alert(msg);
});
}
return false;
});
});
위 부분은 전체 코드 내용, 내가 수정한 부분은 ajax 에 들어가는 url 부분입니다.
action = '/forms/mailer.php';
그리고 mailer.php 파일을 아래와 같이 작성합니다.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
const USER = 'sender@daum.net'; //보내는 사람 이메일
const PASSWORD = 'esfwasdf2'; //비밀번호
$NAME = $_POST['name'];
$MAIL = $_POST['email'];
$PHONE = $_POST['phone'];
$SUBJECT = $_POST['subject'];
$MESSAGE = $_POST['message'];
$HELP_EMAIL = 'help@thermoeye.co.kr';
$mail = new PHPMailer(true);
//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.daum.net";
$mail->SMTPSecure = "ssl";
//Set TCP port to connect to
$mail->Port = 465;
//smtp 설정이 중요합니다. 테스트결과, 다음은 위처럼, 네이버는 아래처럼 해야하더군요
// $mail->Host = "smtp.naver.com";
// $mail->SMTPSecure = "tls";
// $mail->Port = 587;
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = USER;
$mail->Password = PASSWORD;
$mail->CharSet = "utf-8"; //이거 설정해야 한글 안깨짐
//If SMTP requires TLS encryption then set it
$mail->From = USER;
$mail->FromName = "보내는 사람 이름";
$mail->addAddress("abcabc@abc.com", "Recepient Name"); //받는 사람
// $mail->addAddress($HELP_EMAIL, '');
// 테스트 끝나면 받는 주소 바꿔놓기
$mail->isHTML(true);
$mail->Subject = "제목";
$mail->Body = "이메일 내용";
$mail->AltBody = "";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
네이버는 버튼 누르자마자 메일이 오는데,
다음은 3~5분 정도 걸리는 듯 합니다.
근데 생각해보면 그냥 a href에 mailto:이메일주소 로 이메일을 받는게 더 명확하고 좋을 것 같기도 합니다,....
이상 phpmailer 사용법이었습니다.
댓글