본문 바로가기

Backend/Spring

3. STS 로 랜덤한 숫자의 인증코드 이메일로 보내고 인증절차 거치기

1. 우선적으로 이메일 인증을 위한 Dependency 2개 (pom.xml)

 

<dependency>

    <groupId>javax.mail</groupId>

    <artifactId>mail</artifactId>

    <version>1.4.7</version>

</dependency>

 

<dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-context-support</artifactId>

    <version>${org.springframework-version}</version>

</dependency>

 

2. mailSender bean 생성 (root-context.xml)

  1) 받는 계정은 모든 계정이 가능하다. 

  2) 보내는 계정은 구글 계정만 가능하다.

  3) 구글 로그인 후 "보안 수준이 낮은 앱 허용" 을 허용해야 한다. 

 

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">

<property name="host" value="smtp.gmail.com" />

<property name="port" value="587" />

<property name="username" value="구글계정이메일" />

<property name="password" value="구글계정비밀번호" />

<property name="javaMailProperties">

<props>

<prop key="mail.smtp.auth">true</prop>

<prop key="mail.smtp.starttls.enable">true</prop>

</props>

</property>

</bean>

 

 

3. index.jsp (맨처음 view page)에서 이메일 인증을 받고 서비스를 시작할 수 있게 한다.

<form action="emailAuth"> // ->controller 로 연결

You need to be authorized before using our service<br/>

EMAIL <input type="text" name="email" />

<button> Get Auth Code</button>

</form>

 

4.  Controller 

 

@Autowired

private SqlSession sqlSession;

private ImageboardCommand command;

 

@RequestMapping(value="/")

public String index() {

return "index";

}

 

@Autowired

private JavaMailSender mailSender;

 

@RequestMapping("emailAuth")

public String emailAuth(HttpServletRequest request, Model model) {

model.addAttribute("request", request)

model.addAttribute("mailSender", mailSender)

 

command = new EmailAuthCommand();

command.execute(sqlSession, model);

 

return "emailAuthConfirm";

}

 

5. command *(import: interface 로 받아오는 정보: SqlSession, Model)* 

 

public class EmailAuthCommand implements ImageboardCommand {

 

@Override

public void execute(SqlSession sqlSession, Model model) {

 

Map<String , Object> map = model.asMap();

HttpServletRequest request = (HttpServletRequest)map.get("request");

JavaMailSender mailSender = (JavaMailSender)map.get("mailSender");

 

try {

MimeMessage message = mailSender.createMimeMessage();

message.setHeader("Content-type", "text/plain; charset=utf-8");

message.setFrom(new InternetAddress("yunzoo0915@gmail.com"));

InternetAddress to = new InternetAddress(request.getParameter("email"));

 

message.addRecipient(Message.RecipientType.TO, to); // to 1 person

// InternetAddress[] toList = {to}

// message.addRecipients(Message.RecipientType.TO, toList);  // to multiple people

 

message.setSubject("Authorization code Email"); // mail subject

message.setText("To confirm, please enter the Authorization code into our website "); // mail context

 

long authKey = (long)(Math.random()* 1000000L) + 1; // 6자리 랜덤한 숫자 만들기 

message.setText("Authorization code :" + authKey); // mail context 

mailSender.send(message); // send mail

model.addAttribute("authKey", authKey);  // to view (emailAuthConfirm.jsp);

} catch(Exception e) {

 

}

 

}

 

}

 

6. emailAuthConfirm.jsp

<script type="text/javascript">

function fn_emailAuthConfirm(f) { // 위에 커맨드에서 생성한 auth 코드와 사용자가 입력한 코드가 맞는지 검사

// right authKey value: '${authKey}'

// input value : f.authKey.value

if ('${authKey}' ==  f.authKey.value) {

alert(' You have successfully authorized. We will assist you to our service page.');

location.href = 'imageboardList';

} else {

alert('Invalid Auth code. Plaese try again.');

history.back();

}

}

</script>

 

<form>

Please enter Authorization code below. <br/>

<input type="text" name="authKey" />

<input type="button" value="submit" onclick="fn_emailAuthConfirm(this.form)" />

</form>

 

 

 

 

결과는 성공!