spring.mail.host=smtp.gmail.com
spring.mail.port=465
[email protected]
spring.mail.password=wqloionayekqqbel
spring.mail.properties.debug=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com
@ResponseBody
@GetMapping("user/emailAuth")
public Map<String, Integer> checkEmail(String email) throws Exception {
    Map<String, Integer> data = new HashMap<>();
    int code = emailService.sendSimpleMessage(email);
    log.info("인증코드 : " + code);
    data.put("status", 1);
    data.put("code", code);
    return data;
}
package kr.co.farmstory.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Random;

@PropertySource("classpath:application.properties")
@Slf4j
@RequiredArgsConstructor
@Service
public class EmailService {
    @Autowired
    private JavaMailSender javaMailSender;

    //인증번호 생성
    private final String ePw = createKey();

    @Value("${spring.mail.username}")
    private String id;

    public MimeMessage createMessage(String to)throws MessagingException, UnsupportedEncodingException {
        log.info("보내는 대상 : "+ to);
        log.info("인증 번호 : " + ePw);
        MimeMessage message = javaMailSender.createMimeMessage();

        message.addRecipients(MimeMessage.RecipientType.TO, to); // to 보내는 대상
        message.setSubject("Farmstory 회원가입 인증 코드: "); //메일 제목

        // 메일 내용 메일의 subtype을 html로 지정하여 html문법 사용 가능
        String msg="";
        msg += "<h1 style=\\"font-size: 30px; padding-right: 30px; padding-left: 30px;\\">이메일 주소 확인</h1>";
        msg += "<p style=\\"font-size: 17px; padding-right: 30px; padding-left: 30px;\\">아래 확인 코드를 회원가입 화면에서 입력해주세요.</p>";
        msg += "<div style=\\"padding-right: 30px; padding-left: 30px; margin: 32px 0 40px;\\"><table style=\\"border-collapse: collapse; border: 0; background-color: #F4F4F4; height: 70px; table-layout: fixed; word-wrap: break-word; border-radius: 6px;\\"><tbody><tr><td style=\\"text-align: center; vertical-align: middle; font-size: 30px;\\">";
        msg += ePw;
        msg += "</td></tr></tbody></table></div>";

        message.setText(msg, "utf-8", "html"); //내용, charset타입, subtype
        message.setFrom(new InternetAddress(id,"Farmstory")); //보내는 사람의 메일 주소, 보내는 사람 이름

        return message;
    }

    // 인증코드 만들기
    public static String createKey() {
        StringBuffer key = new StringBuffer();
        Random rnd = new Random();

        for (int i = 0; i < 6; i++) { // 인증코드 6자리
            key.append((rnd.nextInt(10)));
        }
        return key.toString();
    }

    /*
        메일 발송
        sendSimpleMessage의 매개변수로 들어온 to는 인증번호를 받을 메일주소
        MimeMessage 객체 안에 내가 전송할 메일의 내용을 담아준다.
        bean으로 등록해둔 javaMailSender 객체를 사용하여 이메일 send
     */
    public int sendSimpleMessage(String to)throws Exception {
        MimeMessage message = createMessage(to);
        try{
            javaMailSender.send(message); // 메일 발송
        }catch(MailException es){
            es.printStackTrace();
            throw new IllegalArgumentException();
        }
        return Integer.parseInt(ePw); // 메일로 보냈던 인증 코드를 서버로 리턴
    }
}
//email
$('#btnSendEmail').click(function(){
	let email = $('input[name=email]').val();
	if(email == ''){
		$('.emailResult').text('이메일을 입력해주세요');
		return;
	}
	
	$('.emailResult').text('인증코드 전송 중입니다. 잠시만 기다리세요...');
	
	$.ajax({
		url: '/Farmstory/user/emailAuth',
		method: 'GET',
		data: {"email": email},
		dataType: 'json',
		success: function(data){
			if(data.status > 0){
				//메일전송 성공
				$('.auth').show();
				$('.emailResult').text('인증코드를 입력해주세요.');
				receivedCode = data.code;
			}else{
				//메일전송 실패
				$('.emailResult').css('color','red').text('메일 전송에 실패했습니다. 다시 시도해주세요');
			}
		}
	});
});

//email code check
$('#btnEmailConfirm').click(function(){
	let code = $('input[name=code]').val();
	if(code == ''){
		alert('이메일 확인 후 코드를 입력해주세요.');
		return;
	}

	if(code == receivedCode){
		$('.auth').hide();
		$('input[name=email]').attr('readonly', true);
		$('.emailResult').css('color','green').text('인증완료 되었습니다.');
		checkEmail = true;
	}
});
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-security'
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.3.0'
	implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
	compileOnly 'org.projectlombok:lombok'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	runtimeOnly 'com.mysql:mysql-connector-j'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testImplementation 'org.springframework.security:spring-security-test'
	implementation 'org.springframework.boot:spring-boot-starter-mail:2.7.1'

}