<label for="user_email" class="email__label"> Email </label>
// 이메일 입력받는 부분
<input id="user_email" name="user_email" class="email_check_input" type="text" autocomplete="off" value="이메일을 입력하세요" />
// 인증메일 보내기 버튼
<button class="email_check_button" type="button" onclick="fn_ConfirmEmailSend()">인증메일 보내기</button>
<label for="user_email_chk" class="email__label"> 인증번호 </label>
// 인증번호 입력받는 부분
<input id="user_email_chk" name="user_email_chk" class="email_check_input" type="text" autocomplete="off" value="인증번호를 입력하세요" />
// 인증번호 확인하기 버튼
<button class="email_check_button" type="button" onclick="fn_EmailConfirm()">이메일 인증하기</button>
<input id="authenticationEmail" type="hidden"/>
// 인증번호 hidden으로 저장해놓는 부분
<input id="authenticationNum" value="${authenticationNum }" type="hidden"/>
let useremail = $("#user_email"); //위에서 미리 저장해둠
//------------------------이메일 인증번호 보내기-----------------------------------
function fn_ConfirmEmailSend() {
if (!fn_emailAuthentication()) { // 이메일 형식 검사 function
return false; // 이메일 형식에 맞지 않는 경우
}
let user_email = useremail.val();
$.ajax({
type: 'post',
url: 'http://localhost:8081/sendEmail.sm',
data: { user_email: user_email },
success: function(data) {
alert("인증번호가 전송되었습니다.");
$("#authenticationEmail").html(data);
console.log(data);
},
error: function(xhr, status, error) {
//오류 발생 시 처리
alert("이메일을 다시 입력해주세요.");
}
});
}
function fn_emailAuthentication() {
let email_chk = /^[A-Za-z0-9_\.\-]+@[A-Za-z0-9\-]+\.[A-Za-z0-9\-]+/;
let email_value = $("#user_email").val();
let flag = true;
if (!email_chk.test(email_value)) {
alert("이메일 형식에 맞춰 입력해주세요");
$("#user_email").val("");
$("#user_email").focus();
flag = false;
}
return flag;
}
//------------------------이메일 인증번호 보내기 끝--------------------------------
//------------------------이메일 인증번호 확인하기---------------------------------
function fn_EmailConfirm() {
let user_email_chk = $("#user_email_chk").val();
let authenticationNum = $("#authenticationNum").val();
if (user_email_chk == authenticationNum) {
alert("인증되었습니다.");
return false;
} else {
alert("인증에 실패하였습니다.");
return false;
}
}
//------------------------이메일 인증번호 확인하기 끝------------------------------
// 이메일 인증 하는 경우
case "/sendEmail.sm":
forward = new GoogleEmailAction().execute(req, resp);
break;
public class MailAuth extends Authenticator { // 인증번호 보내는 메일 정보 입력하는 클래스
PasswordAuthentication pa;
public MailAuth() {
String mail_id = "spacemusic2222@gmail.com";
String mail_pw = "abcdefghijklmnop";
pa = new PasswordAuthentication(mail_id, mail_pw);
} // MailAuth()
public PasswordAuthentication getPasswordAuthentication() {
return pa;
}
} // MailAuth class
public class GoogleEmailAction implements Action { // 이메일 인증하는 action
// 경로 설정 메소드
public ActionForward execute(HttpServletRequest req, HttpServletResponse resp) {
ActionForward forward = new ActionForward();
HashMap<String, String> maildata = new HashMap<>();
maildata.put("user_email", req.getParameter("user_email"));
req.setAttribute("authenticationNum", welcomeMailSend(maildata.get("user_email")));
forward.setRedirect(false);
forward.setPath("/signup.jsp");
return forward;
} // execute()
// ----------------------------------------------------------------------------
// 난수(인증번호) 설정 메소드
public String RandomNum() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 6; i++) {
int n = (int) (Math.random() * 10);
buffer.append(n);
}
return buffer.toString();
} // RandomNum()
//-------------------------------------------------------------------------
// 인증번호 메일 보내는 메소드
public String welcomeMailSend(String recipient){
// user_email을 recipient 파라미터로 받아온다.
Properties prop = System.getProperties();
// 로그인시 TLS를 사용할 것인지 설정
prop.put("mail.smtp.starttls.enable", "true");
// 이메일 발송을 처리해줄 SMTP서버
prop.put("mail.smtp.host", "smtp.gmail.com");
// SMTP 서버의 인증을 사용한다는 의미
prop.put("mail.smtp.auth", "true");
// TLS의 포트번호는 587이며 SSL의 포트번호는 465이다.
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.ssl.trust", "smtp.gmail.com");
prop.put("mail.smtp.ssl.protocols", "TLSv1.2");
Authenticator auth = new MailAuth();
Session session = Session.getDefaultInstance(prop, auth);
MimeMessage msg = new MimeMessage(session);
// 난수 설정 메소드
String authenticationNum = RandomNum();
try {
// 보내는 날짜 지정
msg.setSentDate(new Date());
// 발송자를 지정한다. 발송자의 메일, 발송자명
msg.setFrom(new InternetAddress("spacemusic2222@gmail.com", "표시될 이름"));
// 수신자의 메일을 생성한다.
InternetAddress to = new InternetAddress(recipient);
// Message 클래스의 setRecipient() 메소드를 사용하여 수신자를 설정한다. setRecipient() 메소드로 수신자, 참조,
// 숨은 참조 설정이 가능하다.
// Message.RecipientType.TO : 받는 사람
// Message.RecipientType.CC : 참조
// Message.RecipientType.BCC : 숨은 참조
msg.setRecipient(Message.RecipientType.TO, to);
// 메일의 제목 지정
msg.setSubject("SpaceMusic 인증번호", "UTF-8");
// 메일의 내용 작성
msg.setText("인증번호 : " + authenticationNum, "UTF-8");
// Transport는 메일을 최종적으로 보내는 클래스로 메일을 보내는 부분이다.
Transport.send(msg);
} catch (AddressException ae) {
System.out.println("AddressException : " + ae.getMessage());
} catch (MessagingException me) {
System.out.println("MessagingException : " + me.getMessage());
} catch (UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException : " + e.getMessage());
}
return authenticationNum;
} // welcomeMailSend()
} // GoogleEmailAction class
메일로 전송할 6자리 난수를 생성하는 메서드이다.