Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] 메일 발송기능 구현 완료 #33

Merged
merged 5 commits into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package picasso.server.api.mail;

public class MailPathConstants {
public static String SAMPLE_MAIL = "mail/sample";
}
39 changes: 39 additions & 0 deletions Api/src/main/java/picasso/server/api/mail/TestMailController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package picasso.server.api.mail;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import picasso.server.common.mail.SendMailUtil;

import java.util.HashMap;

/*
* TODO : 해당 컨트롤러 사용법 안내를 위한 TestController로 추후 삭제가 필요합니다.
*/
@Slf4j
@RequestMapping("/mail")
@RequiredArgsConstructor
@RestController
public class TestMailController {
private final SendMailUtil sendMailUtil;

/**
* @param mail 메일을 파라미터로 필요 id@mailHost
* @return
*/
@GetMapping("/test")
public boolean testMail(@RequestParam("mail") String mail) {
return sendMailUtil.sendMail(
mail,
"테스트메일입니다.",
MailPathConstants.SAMPLE_MAIL,
new HashMap<>() {{
put("a", "A변수 데이터 입니다.");
put("b", "B변수 데이터 입니다.");
}});
}

}
16 changes: 16 additions & 0 deletions Api/src/main/resources/templates/mail/sample.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html
lang="ko"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
>
<body>
<div>
<h1> 테스트 SampleMail 입니다.</h1>
<h1 th:text="${a}"></h1>
<br>

<div th:text="${b}"></div>
</div>
</body>
</html>
3 changes: 3 additions & 0 deletions Common/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ dependencies {
api 'org.springframework.boot:spring-boot-starter-aop'
api 'org.springframework.boot:spring-boot-starter-validation'

// Mail
api 'org.springframework.boot:spring-boot-starter-mail'

//File
api 'commons-io:commons-io:2.13.0'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package picasso.server.common.exception;

import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;

import lombok.AllArgsConstructor;
import lombok.Getter;
import picasso.server.common.dto.ErrorDetail;

import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;

@Getter
@AllArgsConstructor
public enum GlobalException implements BaseErrorCode {
Expand All @@ -16,8 +16,9 @@ public enum GlobalException implements BaseErrorCode {
DATE_FORMAT_ERROR(BAD_REQUEST.value(), "날짜 형식을 확인해주세요."),
FILE_UPLOAD_ERROR(INTERNAL_SERVER_ERROR.value(), "파일 업로드 중 오류가 발생하였습니다"),
FILE_DELETE_ERROR(INTERNAL_SERVER_ERROR.value(), "파일 삭제 중 오류가 발생하였습니다"),
FILE_IO_ERROR(INTERNAL_SERVER_ERROR.value(), "파일 변환 중 오류가 발생하였습니다")
;
FILE_IO_ERROR(INTERNAL_SERVER_ERROR.value(), "파일 변환 중 오류가 발생하였습니다"),
ILLEGAL_ARGUMENT_ERROR(BAD_REQUEST.value(), "인자 값 문제로 인한 오류가 발생하였습니다"),
MAIL_SEND_ERROR(INTERNAL_SERVER_ERROR.value(), "메일 발송중 오류가 발생하였습니다");

private final Integer statusCode;
private final String reason;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package picasso.server.common.exception;

import static picasso.server.common.exception.GlobalException.ILLEGAL_ARGUMENT_ERROR;

public class IllegalArgumentException extends BaseException {
public static final BaseException EXCEPTION = new IllegalArgumentException();

public IllegalArgumentException() {
super(ILLEGAL_ARGUMENT_ERROR);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package picasso.server.common.exception;

import static picasso.server.common.exception.GlobalException.MAIL_SEND_ERROR;

public class MailSendException extends BaseException {
public static final MailSendException EXCEPTION = new MailSendException();

public MailSendException() {
super(MAIL_SEND_ERROR);
}
}
71 changes: 71 additions & 0 deletions Common/src/main/java/picasso/server/common/mail/SendMailUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package picasso.server.common.mail;

import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring6.SpringTemplateEngine;
import picasso.server.common.exception.IllegalArgumentException;
import picasso.server.common.exception.MailSendException;

import java.util.Map;

import static org.apache.commons.codec.CharEncoding.UTF_8;

@Slf4j
@Component
@RequiredArgsConstructor
public class SendMailUtil {
private final JavaMailSender javaMailSender;
private final SpringTemplateEngine templateEngine;


/**
* Key는 현재 Mail에 사용중인 변수를, Value는 해당 메일 페이지에 들어갈 값을 입력하면 됩니다.
*
* @param toUser 발송자 메일
* @param title 메일 제목
* @param pagePath ThymeLeaf(HTML)파일 경로
* @param content ThymeLeaf에 들어갈 변수 Map (Not Null!!!)
* @return
*/
public boolean sendMail(String toUser, String title, String pagePath, Map<String, Object> content) {
try {
parameterValidate(toUser, title, content);
MimeMessage message = javaMailSender.createMimeMessage();
message.addRecipients(Message.RecipientType.TO, toUser);
message.setSubject(title, UTF_8);
message.setText(getContent(pagePath, content), UTF_8, "html");
javaMailSender.send(message);
log.info("[SendMail Success] ToUser >>> {}, Title >>> {}, PagePath >>> {}", toUser, title, pagePath);
return true;
} catch (MessagingException e) {
log.error("[SendMail Failed] Exception Reason >>> MessageException, ToUser >>> {}, Title >>> {}, PagePath >>> {}", toUser, title, pagePath);
throw MailSendException.EXCEPTION;
} catch (Exception e) {
log.error("[SendMail Failed] Exception Reason >>> {}, ToUser >>> {}, Title >>> {}, PagePath >>> {}", e.getClass(), toUser, title, pagePath);
throw MailSendException.EXCEPTION;
}
}


//Valid, NotNull를 쓸까했는데... 안먹는걸로 기억이나서..
private void parameterValidate(String toUser, String title, Map<String, Object> content) {
if (toUser == null || title == null || content == null ||
title.isEmpty() || toUser.isEmpty()) {
throw IllegalArgumentException.EXCEPTION;
}
}

// html파일에서 메일내용을 가져옴
private String getContent(String pagePath, Map<String, Object> content) {
Context context = new Context();
content.forEach(context::setVariable);
return templateEngine.process(pagePath, context);
}

}
12 changes: 12 additions & 0 deletions Common/src/main/resources/application-common.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@ naver:
region-name: kr-standard
bucket-name: picasso-bucket


spring:
mail:
host: smtp.gmail.com
port: 587
properties:
mail:
smtp:
auth: true
starttls:
enable: true

---
spring:
config:
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Picasso
[![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2Fdonsonioc2010%2Fpicasso&count_bg=%2379C83D&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=hits&edge_flat=false)](https://hits.seeyoufarm.com)
# Picasso
[홈페이지 링크](http://picasso.jong1.com/) [![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2Fdonsonioc2010%2Fpicasso&count_bg=%2379C83D&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=hits&edge_flat=false)](https://hits.seeyoufarm.com)

---
## 주제
> [!NOTE]
> 미술품 경매 사이트
Expand Down
Loading