본문 바로가기

My Proect/파이널 프로젝트 - CineDate

14일차 - 이메일 인증 구현 에러

build.gradle
	// 이메일 의존성 추가
	implementation group: 'org.springframework.boot', name: 'spring-boot-starter-mail', version: '3.2.8'
	implementation 'javax.mail:javax.mail-api'
	implementation 'org.springframework.boot:spring-boot-starter-validation'
	
	// SpringTemplateEngine 의존성 추가
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'

 

 

 

application.yml

 

 

 

MailDTO
package com.tenco.movie.repository.model;

import jakarta.validation.constraints.NotEmpty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class Mail {
	
	@jakarta.validation.constraints.Email
	@NotEmpty(message = "이메일을 입력해 주세요.")
	private String email;
	
}

 

 

 

MailController
package com.tenco.movie.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.tenco.movie.service.MailSendService;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
@AllArgsConstructor
@ToString
@Builder
@Controller
@RequestMapping("/mail")
public class MailController {
	
	private MailSendService sendService;
	
	@GetMapping("/mail")
	public String mailConfirm(@RequestParam(value = "name", defaultValue = "World") String name, Model model) {
		System.out.println("메일 여기로 들어오는 왔늬");
//		model.addAttribute("name", name);
        return "main"; // templates/main.html 파일을 렌더링
		
	}
	
}

 

 

 

MailSendService
package com.tenco.movie.service;

import java.io.UnsupportedEncodingException;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring6.SpringTemplateEngine;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@Transactional
@Service
@RequiredArgsConstructor
@Data
@AllArgsConstructor
@ToString
@Builder
public class MailSendService {

	@Autowired
	private JavaMailSender emailSender;

	@Autowired
	private SpringTemplateEngine templateEngine;

	private String authNum;

	// 랜덤 인증 코드
	public void createCode() {
		Random random = new Random();
		StringBuffer key = new StringBuffer();

		for (int i = 0; i < 8; i++) {
			int index = random.nextInt(3);

			switch (index) {
			case 0:
				key.append((char) ((int) random.nextInt(26) + 97));
				break;
			case 1:
				key.append((char) ((int) random.nextInt(26) + 65));
			case 2:
				key.append(random.nextInt(9));
				break;
			}
		}
		authNum = key.toString();
	}

	// 메일 양식 신청
	public MimeMessage createEmailForm(String email) throws MessagingException, UnsupportedEncodingException {
		createCode(); // 인증 코드 생성
		String setForm = "hjeong0711@gmail.com";
		String toEmail = email; // 받는 사람
		String title = "[CineDate 이메일 인증]"; // 제목

		MimeMessage message = emailSender.createMimeMessage();
		
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
			helper.setTo(email);
			helper.setSubject(title);
			helper.setFrom(setForm);
			helper.setText(setContext(authNum),true);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return message;
	}

	// 실제 메일 전송
	public String sendEmail(String toEmail) throws MessagingException, UnsupportedEncodingException  {
		// 메일 전송에 필요한 정보 설정
		MimeMessage emailForm = createEmailForm(toEmail);

		// 실제 메일 전송
		emailSender.send(emailForm);

		return authNum;
	}

	// 타임 리프를 이용한 context 설정
	private String setContext(String code) {
		Context context = new Context();
		context.setVariable("code", code);
		return templateEngine.process("main", context); // main.html
	}

}

 

 

 

EmailConfig
package com.tenco.movie.config;

import java.util.Properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ToString
@Configuration
public class EmailConfig {

	@Value("${spring.mail.host}")
	private String host;
	
	@Value("${spring.mail.port}")
	private int port;
	
	@Value("${spring.mail.username}")
	private String username;
	
	@Value("${spring.mail.password}")
	private String password;
	
	@Value("${spring.mail.properties.mail.smtp.auth}")
	private boolean auth;
	
	@Value("${spring.mail.properties.mail.smtp.starttls.enable}")
	private boolean starttlsEnable;
	
	@Value("${spring.mail.properties.mail.smtp.timeout:5000}")
	private int timeout;

	
	@Bean(name = "mail")
	@Primary
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(host);
        mailSender.setPort(port);
        mailSender.setUsername(username);
        mailSender.setPassword(password);
        mailSender.setDefaultEncoding("UTF-8");
        mailSender.setJavaMailProperties(getMailProperties());

        return mailSender;
    }
	
	private Properties getMailProperties() {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", auth);
        properties.put("mail.smtp.starttls.enable", starttlsEnable);
        properties.put("mail.smtp.timeout", timeout);

        return properties;
    }

}

 

결과 화면 ↓

Error

- 이렇게 코드를 작성했는데 메인에서 mail.html이 계속 뜸

- http://localhost:8080/user/signIn 및 다른 링크로 이동이 안됨

 

728x90