· LANGUAGE/└ Java

[ Java ] MimeMessage - 이메일 전송하기

감자도리22 2024. 6. 25. 14:21

환경 : Spring Tool Suite 4

 

https://ggingggang05.tistory.com/202

위에서 적어두긴 했는데.. 한 번 더...

 

 

먼저, Jsoup을 활용하기 위해 의존성을 추가해야 한다. 

 

   - pom.xml

<!-- Jsoup : HTML 해석 도구 -->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.17.2</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

 

 

다음은 이메일을 전송하는 메소드이다.

   - EmailService.java

public void sendWelcomeMail(MemberDto memberDto) throws IOException, MessagingException {
		ClassPathResource resource = new ClassPathResource("templates/welcome-template.html");
		File target = resource.getFile();
		
		StringBuffer buffer = new StringBuffer();
		Scanner sc = new Scanner(target);//파일의 내용을 읽어 줌
		//단, 몇 줄을 읽어줄지 모르므로 다 읽어줄 때까지 while 문 실행
		while(sc.hasNextLine()) {
			buffer.append(sc.nextLine());
		}
		sc.close();
		
        //읽은 내용을 HTML로 해석해서 필요한 정보를 교체한 뒤 전송
        //-Jsoup 필요
		Document document = Jsoup.parse(buffer.toString());//HTML로 해석
		Element who = document.getElementById("who");//#who 탐색
		who.text(memberDto.getMemberNick());//글자 설정
		
		Element link = document.getElementById("login-link");
//		link.attr("href", "http://192.168.30.39:8080/member/login");//현재 내 컴퓨터, 내가 연결되어 있는 공간에서만 접속 가능
		
		//주소를 상황에 맞게 생성하는 도구 - ServletUriComponentsBuilder
		link.attr("href", ServletUriComponentsBuilder
							.fromCurrentContextPath()
							.path("/member/login")
							.build().toUriString());
		
		//이미지 추가
		Element image = document.getElementById("background-img");
		image.attr("src", ServletUriComponentsBuilder
							.fromCurrentContextPath()
							.path("/image/bg.jpg")
							.build().toUriString());
		
		//마임메시지 생성
		MimeMessage message = sender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, false, "UTF-8");
		
		helper.setTo(memberDto.getMemberEmail()); //받는 사람 주소
		helper.setSubject("가입을 환영합니다!"); //메일 제목 설정
		helper.setText(document.toString(), true); //변환된 내용을 본문으로 설정
		
		sender.send(message);
	}

 

 

 외부에서도 해당 로그인 페이지에 접속하고 싶다면,

주소를 상황에 맞게 생성하는 도구인 ServletUriComponentesBuilder를 사용해야 한다.

 

해당 코드는 아래와 같다.

//주소를 상황에 맞게 생성하는 도구 - ServletUriComponentsBuilder
		link.attr("href", ServletUriComponentsBuilder
							.fromCurrentContextPath()
							.path("/member/login")
							.build().toUriString());

 

또한, 이미지를 메일에 삽입하고자 할 때도 동일한 방식으로 구현한다.

(단, 이미지 태그의 변조를 막아두었기 때문에 엑스박스가 나타날 수 있다.)

//이미지 추가
		Element image = document.getElementById("background-img");
		image.attr("src", ServletUriComponentsBuilder
							.fromCurrentContextPath()
							.path("/image/bg.jpg")
							.build().toUriString());

 

 

 

 

이메일에 첨부되는 태그 정보가 들어있는 html 파일을 따로 만들어 보관하는 것이 좋다. (재사용성)

 

 

아이디로 찾는 것이 편하기 때문에 아이디를 부여하여 진행한다.

   - welcome-template.html

<div style="padding:20px; border:1px solid #555; position: relative;">
	<img src="" id="background-img" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; z-index: -1;">
	<h1>
		<span id="who">??</span>님
	</h1>
	<p>
		가입을 진심으로 환영합니다
	</p>
	<h3>
		<a id="login-link" href="#">로그인하기</a>	
	</h3>
</div>

 

 

위의 서비스를 사용하기 위한 컨트롤러이다.

 

   - Controller.java

//회원가입
@GetMapping("/join")
public String join() {
    return "/WEB-INF/views/member/join.jsp";
}
@PostMapping("/join")
public String join(@ModelAttribute MemberDto memberDto,
                        @RequestParam MultipartFile attach) throws IllegalStateException, IOException, MessagingException {

    //회원정보 등록
    memberDao.insert(memberDto);

    //첨부파일 등록
    if(!attach.isEmpty()) {
        int attachNo = attachService.save(attach);//파일저장+DB저장
        memberDao.connect(memberDto.getMemberId(), attachNo);//연결
    }

    //가입 환영 메일 전송
    emailService.sendWelcomeMail(memberDto);

    return "redirect:joinFinish";
}

 

    //가입 환영 메일 전송
    emailService.sendWelcomeMail(memberDto);

    (+) sendWelcomMail()메소드에 DTO를 담아 보내준다

 

 

 

 

개인 공부 기록용입니다:)

728x90