프로필사진
스프링을 이용하여 메일발송해보자 (gmail기반)

2020. 7. 8. 21:59🔴 Spring

300x250

<pom.xml>

<!-- 메일 설정 시작 --> <!-- =================================================== -->
		<!-- javax.mail/mail -->
		<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> <!-- ================================================== -->

<servlet-context.xml> → gmail 활용

<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>

 


<MailSendController.java>

  • MailSender — SimpleMailMessage (메일제목, 단순 텍스트 내용)

package com.bitcamp.mvc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MailSendController {
	
	@Autowired
	MailSender sender; // 타입으로 받을 수 있음
	
	@RequestMapping("/mail/send")
	public String sendMail() {
		
		// 메일 내용 설정
		SimpleMailMessage message = new SimpleMailMessage();
		message.setTo("dnrvy6719@gmail.com"); // 수신자 설정 
		message.setSubject("[광고]임욱표가 단돈 10원 특가세일!"); // 메일 제목 설정
		message.setText("이것은 메일 내용이래"); // 메일 내용 설정
		message.setFrom("ekdms2309@naver.com"); // 발신자 설정
		
		sender.send(message);
		
		return "send OK";
	}
	
}
  • JavaMailSender — MimeMessage(Java Mail API), JavaMailSenderImpl(인터페이스 구현체)
    • MailSender인터페이스 상속받음
    • 파일 첨부 또는 HTML로 구성되어 있을 경우 사용
    • createMimeMessage()
	@ResponseBody
	@RequestMapping("/mail/send2")
	public String sendJavaMailSender(){
		
		MimeMessage message = javaMailSender.createMimeMessage();
		try {
			// 메일 제목설정
			message.setSubject("처음보내는 JavaMailSender", "UTF-8");
			// html 메일 내용
			String htmlStr = "<h1 style=\"color:blue\">안냥안냥</h1><br>"
					+ "<a href=\"http://www/naver/com\">네이버</a>";
			// 내용 설정
			message.setText(htmlStr, "UTF-8", "html"); --> 인코딩, 타입 정할 수 있게 되었음!!
			// To 설정
			message.addRecipient(RecipientType.TO, new InternetAddress("dnrvy6719@gmail.com", "포크", "UTF-8"));
			
			javaMailSender.send(message);
			
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "send OK";
	}
  • MimeMessageHelper 이용 파일 첨부 — DataSource 사용
    • new MimeMessageHelper(MimeMessage객체, Multipart여부, 인코딩타입)
    • MimeMessageHelper.addAttachement() → 파일을 메일에 첨부
    • MimeUtility → 문장 인코딩
// 파일 첨부해서 전송
	@ResponseBody
	@RequestMapping("/mail/send3")
	public String sendFileAttach() {
		
		MimeMessage message = javaMailSender.createMimeMessage();
		
		try {
			
			MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");
			// 제목
			messageHelper.setSubject("[제목]욱표야 안뇽?");
			// 내용 html
			String htmlStr = "<h1>파일 다운받아!!!어서!!!</h1>";
			// 내용설정
			messageHelper.setText(htmlStr, true);
			// To 설정
			messageHelper.setTo(new InternetAddress("dnrvy6719@gmail.com", "포크", "UTF-8"));
			// 첨부할 파일 객체 생성
			DataSource dataSource = new FileDataSource("C:\\Users\\ekdms\\Desktop\\warm.gif"); //절대경로
			// MimeMessageHelper 파일 객체를 추가
			messageHelper.addAttachment(MimeUtility.encodeText("warm.gif", "UTF-8", "B"), dataSource);
			
			// 전송
			javaMailSender.send(message);
			
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "send OK";
	}

<MemberInfo.java>

package com.bitcamp.mm.member.domain;

import java.util.Date;
import java.util.Random;

import com.fasterxml.jackson.annotation.JsonIgnore;

// usebean Class
public class MemberInfo {

	// 각 변수의 저근 제어지시자는 private
	private int idx;
	private String uId;
	private String uPw;
	private String uName;
	private String uPhoto;
	private Date regDate;
	
	@JsonIgnore
	private char verify;
	private String code;

	// default 생성자 필수
	public MemberInfo() {
		this.regDate = new Date();
		this.code = getRandomCode();
	}

	public char getVerify() {
		return verify;
	}

	public void setVerify(char verify) {
		this.verify = verify;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public MemberInfo(String uId, String uPw, String uName, String uPhoto) {
		super();
		this.uId = uId;
		this.uPw = uPw;
		this.uName = uName;
		this.uPhoto = uPhoto;
		this.regDate = new Date();
		this.code = getRandomCode();
	}

	public MemberInfo(int idx, String uId, String uPw, String uName, String uPhoto, Date regDate) {
		super();
		this.idx = idx;
		this.uId = uId;
		this.uPw = uPw;
		this.uName = uName;
		this.uPhoto = uPhoto;
		this.regDate = regDate;
		this.code = getRandomCode();
	}

	// 변수들의 Getter/Setter 시작

	public String getuId() {
		return uId;
	}

	public int getIdx() {
		return idx;
	}

	public void setIdx(int idx) {
		this.idx = idx;
	}

	public void setuId(String uId) {
		this.uId = uId;
	}

	public String getuPw() {
		return uPw;
	}

	public void setuPw(String uPw) {
		this.uPw = uPw;
	}

	public String getuName() {
		return uName;
	}

	public void setuName(String uName) {
		this.uName = uName;
	}

	public String getuPhoto() {
		return uPhoto;
	}

	public void setuPhoto(String uPhoto) {
		this.uPhoto = uPhoto;
	}

	public Date getRegDate() {
		return regDate;
	}

	public void setRegDate(Date regDate) {
		this.regDate = regDate;
	}

	// 데이터 확인을 위한 toString 오버라이딩
	@Override
	public String toString() {
		return "MemberInfo [idx=" + idx + ", uId=" + uId + ", uPW=" + uPw + ", uName=" + uName + ", uPhoto=" + uPhoto
				+ ", regDate=" + regDate + "]";
	}
	
	// 2019.08.21 난수 발생시키기
	public String getRandomCode() {
		
		Random rand = new Random(System.nanoTime());
		StringBuffer sb = new StringBuffer();
		
		// 총 20문자 길이의 난수를 생성
		for(int i=0; i<20; i++) {
			// 랜덤으로 true 또는 false 생성
			if(rand.nextBoolean()) {
				sb.append(rand.nextInt(10)); //0~9까지 난수 생성
			} else {
				sb.append((char)(rand.nextInt(26)+97)); //알파벳 난수 생성
			}
		}
		
		System.out.println("생성된 난수: "+sb);
		
		return sb.toString();
		
	}
	
	// 화면 결과 출력을 위한 HTML 코드 반환
	public String makeHtmlDiv() {
		String str = "";

		str += "<div class=\"mInfor\"> \n";
		str += "	<h3> \n";
		str += "		" + uId + "(" + uName + ")\n";
		str += "	</h3> \n";
		str += "	<p> \n";
		str += "		" + uPw;
		str += "	</p> \n";
		str += "</div> \n";

		return str;
	}

	// MemberInfo 객체 -> LoginInfo 객체 반환
	public LoginInfo toLoginInfo() {

		return new LoginInfo(uId, uName, uPhoto, regDate);

	}
	
	// 비밀번호 체크 확인
	// 2019.07.25 메서드 추가
	public boolean pwChk(String pw) {
		return uPw != null && uPw.trim().length()>0 && uPw.equals(pw);
	}
	
}

<MailSenderService.java>

package com.bitcamp.mm.member.service;

import java.io.UnsupportedEncodingException;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import com.bitcamp.mm.member.dao.MemberSessionDao;
import com.bitcamp.mm.member.domain.MemberInfo;

@Service("mailSenderService")
public class MailSenderService {
	
	@Autowired
	private SqlSessionTemplate template;
	
	private MemberSessionDao dao;
	
	@Autowired
	private JavaMailSender sender;
	
	public int verify(String id) {
		int result = dao.verify(id);
		return result;
	}
	
	public MemberInfo getMemberInfo(String id) {
		dao = template.getMapper(MemberSessionDao.class);
		MemberInfo memberInfo = dao.selectMemberById(id);
		return memberInfo;
	}
	
	public int send(MemberInfo memberInfo) {
		
		MimeMessage message = sender.createMimeMessage();
		
		try {
			
			message.setSubject("회원가입 메세지", "UTF-8");
			String htmlMsg = "<h1>회원가입 츄카링~</h1>"
					+ "<a href=\"http://localhost:9090/mm/member/regCheck?code="+memberInfo.getCode()+"&id="+memberInfo.getuId()+" \">가입 인증하기</a><br>"
					+ "인증번호 :" + memberInfo.getCode();
			
			message.setText(htmlMsg, "UTF-8", "html");
			message.setFrom(new InternetAddress("ekdms2309@naver.com"));
			message.addRecipient(RecipientType.TO, new InternetAddress(memberInfo.getuId(), "USER", "UTF-8"));
			
			sender.send(message);
			
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return 1;
	}
	
	
}

<MemberRegController.java>

package com.bitcamp.mm.member.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.bitcamp.mm.member.domain.RequestMemberRegist;
import com.bitcamp.mm.member.service.MailSenderService;
import com.bitcamp.mm.member.service.MemberRegService;

@Controller
@RequestMapping("/member/regist")
public class MemberRegController {
	
	@Autowired
	private MemberRegService registService;
	@Autowired
	private MailSenderService mailSenderService;
	
	// member/regist => 
	// 1. nav에서 '회원가입' 클릭 -> get방식  
	// 2. 회원가입 정보 적고 submit -> post방식
	
	@RequestMapping(method = RequestMethod.GET)
	public String getForm() {
		return "member/registForm";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String memberRegist(RequestMemberRegist regist,
				HttpServletRequest request,
				Model model
			) {
		
		System.out.println(regist);
		
		int resultCnt = registService.memberInsert(request, regist);
		model.addAttribute("rCnt",resultCnt);
		
		mailSenderService.send(regist.getuId());
		
		return "member/memberRegist";
	}
}

<VerifyController.java>

package com.bitcamp.mm.member.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bitcamp.mm.member.domain.MemberInfo;
import com.bitcamp.mm.member.service.MailSenderService;

@Controller
public class VerifyController {
	
	@Autowired
	MailSenderService mailSenderService;
	
	@RequestMapping("member/regCheck")
	public String regCheck(
			@RequestParam("code") String code,
			@RequestParam("id") String id,
			Model model
			) {
		
		int result = 0;
		if(code != null) {
			result = mailSenderService.verify(id);
		}
		
		model.addAttribute("result",result);
		model.addAttribute("code",code);
		
		return "member/regCheck";
	}
	
	@RequestMapping("member/sendEmail")
	@ResponseBody
	public String sendEmail(
			@RequestParam("id") String id
			) {
		
		MemberInfo memberInfo = mailSenderService.getMemberInfo(id);
		int result = mailSenderService.send(memberInfo);
		
		return result>0?"SUCCESS":"FAIL";
	}
}
300x250