mintmint
200
2020-11-23 13:33:53 작성 2020-11-23 13:40:50 수정됨
3
260

spring 이메일 전송시 smtp 설정방법


smtp 가 설정이 안되어 있어서 그런건가요??? 혹시 설정방법좀 설명부탁드려요...

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
  nested exception is:
	java.net.ConnectException: Connection refused: connect
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
	at javax.mail.Service.connect(Service.java:297)
	at javax.mail.Service.connect(Service.java:156)
	at javax.mail.Service.connect(Service.java:105)
	at javax.mail.Transport.send0(Transport.java:168)
	at javax.mail.Transport.send(Transport.java:98)
	at com.spring.virtualEmail.emailCheck.sendEmail(emailCheck.java:56)
	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:317)
	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)
Caused by: java.net.ConnectException: Connection refused: connect
	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
	at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
	at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
	at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
	at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
	at java.net.PlainSocketImpl.connect(Unknown Source)
	at java.net.SocksSocketImpl.connect(Unknown Source)
	at java.net.Socket.connect(Unknown Source)
	at java.net.Socket.connect(Unknown Source)
	at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
	at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
	... 82 more



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;
import org.springframework.web.bind.annotation.RequestParam;

public class emailCheck {
	@Autowired
	private JavaMailSender mailSender;
	
	public void sendEmail(String vEmail, String authNum) {
		String host = "smtp.gmail.com"; // smtp 서버
		String subject = "virtualHompage 인증번호 전달";
		String fromName = "가상홈페이지 관리자";
		String from = "구글@gmail.com"; // 보내는 메일
		String to1 = vEmail;
		System.out.println("send to1 " +to1);
		System.out.println("send vEmail " + 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("구글이메일", "비밀번호");
						}
			});
			
			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();
	}
	
}


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);
		System.out.println(vEmail);
		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){
			url = "/emailAuth?vEmail="+vEmail;
			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>


servlet-context.xml

<!-- 회원가입 메일 인증 -->
	<beans:bean id="mailSender"	class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<beans:property name="host" value="smtp.gmail.com" />
		<beans:property name="port" value="587" /><!-- 465 or 25 -->
		<beans:property name="username" value="이메일" />
		<beans:property name="password" value="비밀번호" />
		<beans:property name="defaultEncoding" value="utf-8" />
		<beans:property name="javaMailProperties">
			<beans:props>
				<beans:prop key="mail.transport.protocol">smtp</beans:prop>
				<beans:prop key="mail.smtp.auth">true</beans:prop>
				<beans:prop key="mail.smtp.starttls.enable">true</beans:prop>
				<beans:prop key="mail.debug">true</beans:prop>
			</beans:props>
		</beans:property>
	</beans:bean>

	
	<beans:bean id = "email" class = "com.spring.virtualEmail.emailCheck"/>



0
  • 답변 3

  • 혹등혹등
    649
    2020-11-23 13:35:22
    설정한 코드도 있어야 하지 않을까요?
  • mintmint
    200
    2020-11-23 13:41:09

    코드 다시 올렸습니다.

  • mintmint
    200
    2020-11-23 14:25:26

    포트를 465로 해야하는군요... 다른곳은 다 587로 설정하던데..

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