본문 바로가기
Spring

Spring #12 : 이메일 기능 (230131)

by haheehee 2023. 1. 31.

이메일로 로그인 확인하는 기능!!

 

- 스프링에선 이메일 라이브러리를 이용해 쉽게 이메일 기능을 구현 가능

- 구글의 SMTP 서버을 이용해서 이메일 기능 구현

 

- pom.xml 파일에서 이메일 기능을 사용하기 위해 코어 스프링 라이브러리 버전을 4.1.1.RELEASE로 변경해야 한다.

		<!-- 이메일 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>javax.mail-api</artifactId>
			<version>1.5.4</version>
		</dependency>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.5.3</version>
		</dependency>

pom.xml에 들어가는 dependency태그 (관련 라이브러리 추가)

 

- host는 smtp를 사용

 

- 네이버 메일로 들어가 로그인 한 후, 환경설정

환경설정으로 들어가기

POP3/IMAP설정- IMAP/SMTP설정 - 사용함 체크 - 저장

 


스프링 - 이메일 사용하기 실습 #1

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spring</groupId>
	<artifactId>promvn04</artifactId>
	<name>promvn04</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>4.1.1.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	
...
		
		<!-- 이메일 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>javax.mail-api</artifactId>
			<version>1.5.4</version>
		</dependency>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.5.3</version>
		</dependency>
		
...

pom.xml

스프링 라이브러리 버전을 4.1.1.RELEASE로 변경

라이브러리 태그 추가

 

...
<!--The definition of the Root Spring Container shared by all Servlets and Filters-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/*.xml</param-value>
	</context-param>
...

web.xml

설정 파일이 여러 개인 경우 톰캣 컨테이너 실행 시

spring폴더 안의 모든 설정파일을 읽도록 태그 추가

 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="smtp.naver.com" />
		<property name="port" value="587" />
		<property name="username" value="~~~~~~~~~" />
		<property name="password" value="~~~~~~~~~~~~~*" />
		<property name="javaMailProperties">
			<props>
				<prop key="mail.transport.protocol">smtp</prop>
				<prop key="mail.smtp.auth">true</prop>
				<prop key="mail.smtp.starttls.enable">true</prop>
				<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
				<prop key="mail.debug">true</prop>
			</props>
		</property>		
	</bean>
	
	<!--You can have some pre-configured messagess also which are ready to send-->
	<bean id="preConfiguredMessage" class="org.springframework.mail.SimpleMailMessage">
		<property name="to" value="~~~~~~전송할메일주소" />
		<property name="from" value="~~~~~받을메일주소" />
		<property name="subject" value="테스트 메일입니다" />
	</bean>
</beans>

mail-context.xml

property의 host와 port는 위의 네이버 메일 환경설정으로 들어가서

해당 정보를 복사-붙여넣기로 하면 된다.

물결로 된 부분은 본인의 진짜 메일과 비밀번호!

 

package com.spring.promvn04.ex03;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service("mailService")
public class MailService {
	@Autowired
	private JavaMailSender mailSender;
	@Autowired
	private SimpleMailMessage preConfiguredMessage;
	
	@Async
	public void sendMail(String to, String subject, String body) {
		MimeMessage message = mailSender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");
			messageHelper.setFrom("~~~~~~~@naver.com", "하히");
			messageHelper.setSubject(subject);
			messageHelper.setTo(to);
			messageHelper.setText(body);
			mailSender.send(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Async
	public void sendPreConfiguredMail(String message) {
		SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage);
		mailMessage.setText(message);
		mailSender.send(mailMessage);
	}
}

MailService.java

 

package com.spring.promvn04.ex03;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@EnableAsync
public class MailController {
	@Autowired
	private MailService mailService;
	
	@RequestMapping(value="/sendMail.do", method=RequestMethod.GET) 
	public void sendSimpleMail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		mailService.sendMail("~~~~~~~@naver.com", "testMail", "안녕하세요");
		mailService.sendPreConfiguredMail("test Mail sending");
		out.print("메일을 보냈습니다.");
	}
}

MailController.java

 

 

-- 결과 --

서버 실행 후, localhost:8080/promvn04/sendMail.do로 요청

 

이렇게 메일이 2개 온 것을 확인할 수 있다.

 

 

 


스프링 - 이메일 사용하기 실습 #2

 

나머지는 동일하되, MailController와 MailService를 변경해주면 된다.

 

package com.spring.promvn04.ex03;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service("mailService")
public class MailService {
	@Autowired
	private JavaMailSender mailSender;
	@Autowired
	private SimpleMailMessage preConfiguredMessage;
	
	@Async
	public void sendMail(String to, String subject, String body) {
		MimeMessage message = mailSender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");
			messageHelper.setFrom("~~~~~~~~@naver.com", "hahee");
			messageHelper.setSubject(subject);
			messageHelper.setTo(to);
			messageHelper.setText(body, true);
			mailSender.send(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Async
	public void sendPreConfiguredMail(String message) {
		SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage);
		mailMessage.setText(message);
		mailSender.send(mailMessage);
	}
}

MailService.java

 

package com.spring.promvn04.ex03;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@EnableAsync
public class MailController {
	@Autowired
	private MailService mailService;
	
	@RequestMapping(value="/sendMail.do", method=RequestMethod.GET) 
	public void sendSimpleMail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		StringBuffer sb = new StringBuffer();
		sb.append("<html><body>");
		sb.append("<meta http-equiv='Content-Type' content='text/html; charset=euc-kr'>");
		sb.append("<h1>"+"티스토리 소개"+"</h1><br>");
		sb.append("<a href='https://hhahee.tistory.com/'>");
		sb.append("<img src='http://image.kyobobook.co.kr/images/book/xlarge/425/x9788956746425.jpg' /></a></br>");
		sb.append("</a>");
		sb.append("<a href='https://blog.naver.com/~~~~~'>블로그보기</a>");
		sb.append("</body></html>");
		String str=sb.toString();
		mailService.sendMail("~~~~~~~~~@naver.com", "하히티스토리/블로그 소개", str);
		
		out.print("메일을 보냈습니다.");
	}
}

MailController.java

 

 

-- 결과 --

사진을 클릭하면 티스토리로,

블로그보기 하이퍼링크를 클릭하면 블로그로 사이트 이동이 된다.

따로 이미지를 넣어보았다.

댓글