본문 바로가기
  • Welcome J-Kyu Tstory
Spring

[spring]스프링으로 메일 발송 하기

by regularity 2022. 5. 15.
728x90

 

1. 메일 계정 생성하기 (구글) -> 보안 수준이 낮은 앱의 액세스를 허용으로

 

2.  메일발송 기능을 추가하기 위한 pom.xml 디펜던시 추가

	<!-- 메일 발송 기능을 위한 dependency 추가 -->
		<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>4.3.8.RELEASE</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-email -->
		<dependency>
		    <groupId>org.apache.commons</groupId>
		    <artifactId>commons-email</artifactId>
		    <version>1.5</version>
		</dependency>
		<!-- 메일 발송 기능을 위한 dependency 추가 END-->

 

3.  root-context.xml 에 bean 설정

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

		
	<!-- gmail설정 (mailSender bean 생성)-->
		<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="자신의 계정@gmail.com"/> <!-- 자신의 이메일 아이디 -->
		 	<property name="password" value="비밀번호"/> <!-- 자신의 비밀번호 -->
			 <!-- 보안연결 TLS과 관련된 설정 -->
		     <property name="javaMailProperties">
			    <props>
			       <prop key="mail.smtp.starttls.enable">true</prop>
			       <prop key="mail.smtp.auth">true</prop>
			       <prop key="mail.transport.protocol">smtp</prop>
			       <prop key="mail.debug">true</prop>
			       <prop key="mail.smtp.ssl.trust">smtp.gmail.com</prop>
				   <prop key="mail.smtp.ssl.protocols">TLSv1.2</prop>
			    </props>
		     </property>
	     </bean>
		
</beans>

4. mailSend.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
	<title>Home</title>
</head>
<body>
<h1>Reservation Mail Send</h1>
<hr><br>

<div>
	<form action="${pageContext.request.contextPath}/mail/mailSend" method="post">
		<div class="input_1">
			<laber>성</laber>
			<input type="text" name="name" placeholder="Name" required="">
		</div>	
		<div class="input_2">
			<laber>이름</laber>
			<input type="text" name="last_name" placeholder="last_Name" required="">
		</div>	
		<div class="input_3">
			<input type="email" name="email" placeholder="Email" required="">
		</div>	
		<div class="input_4">
			<textarea type="message" name="Message" placeholder="Message" required=""></textarea>
		</div>	
		<div>
			<div class="click">
				<input type="submit" value="SEND">			
			</div>
		</div>
	
	</form>
</div>

</body>
</html>

 

 

5. MailController.java

package com.order.controller;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
@RequestMapping("/mail/*")
public class MailController {

	@Autowired
	private JavaMailSender mailSender;
	
	private static final Logger logger = LoggerFactory.getLogger(MailController.class);
    
	//----------------------------메일발송 JSP 로 이동------------------------
	@RequestMapping(value = "/mailSend", method = RequestMethod.GET)
	public void getMailSend() {
		logger.info("메일발송 JSP진입");
	}
	
	//--------------------------------메일발송-----------------------------
	//mailSend 코드
	@RequestMapping(value = "/mailSend", method = RequestMethod.POST)
	public String mailSend(HttpServletRequest request,String name,String last_name,String email,String phone,String message) {
		try {
			
			MimeMessage mimeMessage = mailSender.createMimeMessage();
		   // MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
		    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
		    logger.info("Message {}", mimeMessage);
 
		    //test용 메일 내용
		    messageHelper.setFrom("orderbyticket@gmail.com"); // 보내는사람 이메일 여기선 google 메일서버 사용하는 아이디를 작성하면됨
		    messageHelper.setTo("수신메일주소@naver.com"); // 받는사람 이메일
		    messageHelper.setSubject("[티켓예약] 안녕하세요 ORDER BY TICKET 입니다" ); // 메일제목
		    //messageHelper.setText("예약하신 회원님은"+ name + last_name + "입니다."+" 연락처는 " + phone + "입니다. 입력한 Email은 " + email + "입니다."); // 메일 내용
		    //messageHelper.setText("text/html","<div style='border: 3px solid blue'><a href='https://www.naver.com/'>message</a></div>");
		    //로그인 폼 테스트HTML ->//messageHelper.setText("text/html","<html> <head> <meta name=\"viewport\" content=\"width=device-width, height=device-height, minimum-scale=1.0, maximum-scale=1.0, initial-scale=1.0\"> </head> <body> <header> <h2>Login</h2> </header> <form action=\"\" method=\"POST\"> <div class=\"input-box\"> <input id=\"username\" type=\"text\" name=\"username\" placeholder=\"아이디\"> <label for=\"username\">아이디</label> </div> <div class=\"input-box\"> <input id=\"password\" type=\"password\" name=\"password\" placeholder=\"비밀번호\"> <label for=\"password\">비밀번호</label> </div> <div id=\"forgot\">비밀번호 찾기</div> <input type=\"submit\" value=\"로그인\"> </form> </body> </html>");
		    
		    mailSender.send(mimeMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "redirect:/";
	}
	
}

 

5.1 HTML 형식으로 보내기

(※ 메일 내용의 폼을 꾸며서 보내기위해서는 HTML 형식으로 보내야 태그가 적용됨)

 messageHelper.setText("text/html","<html>메일내용</html>");
 
 위와같은 형식으로 보내야 인식됨

 

6. HTML 형태의 메일 발송 완료



※구글 보안정책 변경으로 사용 불가 -> 네이버 메일기능으로 변경

728x90

댓글