mintmint
200
2020-11-23 11:36:25 작성 2020-11-23 11:39:27 수정됨
2
280

스프링 Gmail 이용 이메일 보내기 오류


이메일로 인증받아 아이디나 비밀번호 찾기 구현할려고 구글에 검색해보면서 시도하고있는데,, 계속 오류가 발생해서 질문합니다....


root-context.xml

<bean id = "mailSender" class = "org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name = "host" value = "stmp.gmail.com" />
		<property name = "port" value = "587" />
		<property name = "defaultEncoding" value = "utf-8" />
		<property name = "username" value = " *******@gmail.com" />
		<property name = "password" value = "  ********* " />
		
		<property name = "javaMailProperties" >
			<props>
				<prop key = "mail.smtp.starttls.enable">true</prop>
				<prop key="mail.smtp.auth">true</prop>
			</props>
		</property>
	</bean>


HomePageController.java

@RequestMapping("emailAuth")
	public ModelAndView emailAuth(HttpServletResponse response, HttpServletRequest request, String vEmail) throws Exception{
		emailCheck email = new emailCheck();
		vEmail = request.getParameter("vEmail");
		String authNum = "";
		authNum = email.RandoNum();
		
		email.sendEmail(vEmail,authNum);
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("Find/Id/emailAuth");
		modelAndView.addObject("vEmail", vEmail);
		modelAndView.addObject("authNum", authNum);
		return modelAndView;
	} 



emailIdFindForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>

	function emailCheck(vEmail){
		var email = document.getElementById("vEmail").value;
		if(email.trim()==""){
			 alert("이메일을 먼저 입력하세요");
			 document.regForm.vEmail.focus()
		 }
		else if(vEmail){
			var url = "/emailCheck";
			url = "/emailAuth";
			window.open(url,"post","width=300, height=100");				
		 }
	}

</script>
<meta charset="UTF-8">
<title>아이디 찾기</title>
</head>
<body>
<div align = "left">
	<span>
		<a href = "/virtualHomePage"><img src = "/resources/image/home.png" class = "EmailIdFindFormImageStyle"/></a> 
		<a href = "/virtualHomePage/idFind"><label class = "idFindlabel">아이디 찾기</label></a>
		<a href = "/virtualHomePage/passwordFind"><label class = "passwordFindlabel">비밀번호 찾기</label></a>
	</span>
	<br/><br/><br/><br/><br/><br/>
</div>
<div align = "center">
	<h3>가입한 이메일로 아이디 찾기</h3>
	<hr width = "400" color = "red"/>
	<table cellpadding = "0" cellspacing = "0" border = "1">
		<form:form action = "/idFindResult" commandName="VVO" method = "post" >
			<tr>
				<td>이름</td>
				<td><form:input path = "vName" /></td>
			</tr>
			<tr>
				<td>이메일</td>
				<td>
					<form:input path = "vEmail" id = "vEmail"/>
					<button type = "button" action = "emailAuth" onClick = "emailCheck(this.form.vEmail.value)">인증하기</button>
				</td>
			</tr>
			<tr>
				<td colspan = "2"><input type = "submit" value = "아이디 찾기"/></td>
			</tr>
		</form:form>
	</table>
</div>
</body>
</html>




emailCheck.java

package com.spring.virtualEmail;


import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.InternetAddressEditor;
import org.springframework.mail.javamail.JavaMailSender;

public class emailCheck {
	@Autowired
	private JavaMailSender mailSender;
	
	public void sendEmail(String vEmail, String authNum) {
		String host = "smtp.gmail.com"; // smtp 서버
		String subject = " 인증번호 전달";
		String fromName = " 관리자";
		String from = " ********@gmail.com"; // 보내는 메일
		String to1 = vEmail;
		
		String content = "인증번호 [" + authNum + "]";
		
		try {
			Properties props = new Properties();
			// Gmail SMTP 사용시
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", host);
			props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.prot","587");
			props.put("mail.smtp.user", from);
			props.put("mail.smtp.auth", "true");
			
			Session mailSession = Session.getInstance(props, 
					new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(" ******@gmail.com", " *********** ");
						}
			});
			
			Message message = new MimeMessage(mailSession);
			message.setFrom(new InternetAddress(from,MimeUtility.encodeText(fromName, "UTF-8", "B"))); // 보내는 사람 설정
			
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1)); // 받는 사람설정
			message.setSubject(subject);
			message.setSentDate(new java.util.Date()); // 보내는 날짜 설정
			message.setContent(content, "text/html;charset=utf-8");
			
			Transport.send(message);
		} catch(MessagingException me) {
			me.printStackTrace();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	public String RandoNum() {
		StringBuffer buffer = new StringBuffer();
		for(int i = 0; i<= 6; i++) {
			int n = (int)(Math.random() * 10);
			buffer.append(n);
		}
		return buffer.toString();
	}
	
}


emailAuth.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
	function check(){
		var form = document.authenform;
		var authNum = ${authNum};
		if(!form.authnum.value){
			alert("인증번호를 입력하세요");
			return false;
		}
		if(form.authnum.value != authNum){
			alert("인증번호가 일치하지 않습니다. 인증번호를 다시 입력해주세요.");
			form.authnum.value = "";
			return false;
		}
		if(form.authnum.value == authNum){
			alert("인증완료");
			opener.document.userinput.mailCheck.value = "인증완료";
			self.close;
		}
	}
</script>
<meta charset="UTF-8">
<title>이메일 인증</title>
</head>
<body>
	<center>
		<div align = "center">
			<form  method = "post" name = "authenform" onSubmit = "return check();">
				<input type = "text" name ="authnum"/><br/><br/>
				<input type = "submit" value = "인증하기"/>
			</form>	
		</div>
	</center>
</body>
</html>



에러코드

java.lang.NullPointerException
	at javax.mail.internet.InternetAddress.parse(InternetAddress.java:595)
	at javax.mail.internet.InternetAddress.parse(InternetAddress.java:555)
	at javax.mail.internet.InternetAddress.<init>(InternetAddress.java:91)
	at com.spring.virtualEmail.emailCheck.sendEmail(emailCheck.java:49)
	at com.spring.HomeController.HomePageController.emailAuth(HomePageController.java:141)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:854)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:765)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
	at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
	at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347)
	at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:165)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:319)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Unknown Source)


에러코드를 보면


message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));


email.sendEmail(vEmail,authNum); 


InternetAddress(to1)<< 이부분이 문제인거 같은데 뭐를 수정해야 할까요...???


0
  • 답변 2

  • 밥도둑계장
    799
    2020-11-23 11:51:39

    말그대로 null point 같은데

    컨트롤러에서 vEmail 제대로 들어오는거 확인하셧나요?

  • mintmint
    200
    2020-11-23 12:59:48 작성 2020-11-23 13:07:17 수정됨

    아... null로 들어오는군요..

  • 로그인을 하시면 답변을 등록할 수 있습니다.