스프링과 JPA 기반 웹 애플리케이션 개발 #52 HTML 이메일 전송하기

Jake Seo·2021년 6월 14일
1

스프링과 JPA 기반 웹 애플리케이션 개발 #52 HTML 이메일 전송하기

해당 내용은 인프런, 스프링과 JPA 기반 웹 애플리케이션 개발의 강의 내용을 바탕으로 작성된 내용입니다.

강의를 학습하며 요약한 내용을 출처를 표기하고 블로깅 또는 문서로 공개하는 것을 허용합니다 라는 원칙 하에 요약 내용을 공개합니다. 출처는 위에 언급되어있듯, 인프런, 스프링과 JPA 기반 웹 애플리케이션 개발입니다.

제가 학습한 소스코드는 https://github.com/n00nietzsche/jakestudy_webapp 에 지속적으로 업로드 됩니다. 매 커밋 메세지에 강의의 어디 부분까지 진행됐는지 기록해놓겠습니다.


HTML 이메일 전송하기

  • 타임리프 템플릿으로 이메일 템플릿 작성
<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>제이크 스터디</title>
</head>
<body>
  <div>
    <p class="lead">안녕하세요. <span th:text="${nickname}"></span></p>
    
    <h2 th:text="${message}">메세지</h2>
    <div>
      <a th:href="@{${host} + ${link}}" th:text="${linkName}">link name</a>
      <p>링크가 동작하지 않는다면, URL을 복사해서 사용하는 웹 브라우저에 붙여넣으세요.</p>
      <small th:text="${host + link}"></small>
    </div>
  </div>
  <footer>
    <small class="d-block mb-3 text-muted">제이크스터디&copy; 2021</small>
  </footer>
</body>
</html>
  • 템플릿 엔진으로 HTML 본문 채워 넣기
    • TemplateEngine
    • Context
  • 애플리케이션 설정 추가
    • AppProperties 추가
app.host=http://localhost:8080

simple-link.html

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>제이크 스터디</title>
</head>
<body>
<div>
  <p class="lead">안녕하세요. <span th:text="${nickname}"></span></p>

  <h2 th:text="${message}">메세지</h2>
  <div>
    <a th:href="@{${host} + ${link}}" th:text="${linkName}">link name</a>
    <p>링크가 동작하지 않는다면, URL을 복사해서 사용하는 웹 브라우저에 붙여넣으세요.</p>
    <small th:text="${host + link}"></small>
  </div>
</div>
<footer>
  <small class="d-block mb-3 text-muted">제이크스터디&copy; 2021</small>
</footer>
</body>
</html>

AppProperties 클래스 생성

// 스프링 부트에서 Properties를 받아올 수 있음
@Data
@Component
@ConfigurationProperties("app")
public class AppProperties {
    private String host;
}

위와 같이 @ConfigurationProperties 애노테이션을 이용하면, application.properties에 있는 값들을 빈의 멤버 값으로 가져올 수 있다. 뒤의 value 엘리먼트로 "app"이 들어있는데, 이 "app"이 의미하는 것은 app.xxxx를 가져오겠다는 것이다.

application.properties 내용 추가

app.host=http://localhost:8080

AccountService

getMailHtmlText() 메소드

    public String getMailHtmlText(String link, String nickname, String linkName, String message, String host) {
        Context context = new Context();
        context.setVariable("link", link);
        context.setVariable("nickname", nickname);
        context.setVariable("linkName", linkName);
        context.setVariable("message", message);
        context.setVariable("host", host);

        String mailText = templateEngine.process("mail/simple-link.html", context);
        return mailText;
    }

위는 link, nickname, linkname, message, host 등 매개변수를 넘겨주면, mail/simple-link.html에 있는 템플릿을 통해서 메일로 보낼 문자열을 만들어주는 메소드이다.

위의 ContextthymeleafContext이며, templateEnginethymeleaf 의존성을 사용하면 제공되는 TemplateEngine 타입의 빈을 가져온 것이다.

sendAccountConfirmEmail() 메소드

    public void sendAccountConfirmEmail(Account account) {
        // 아래와 같이만 쓰면, resources/templates/mail/simple-link.html 자동으로 찾아감
        account.generateEmailCheckToken();

        String mailText = getMailHtmlText(
                "/check-email-token?token=" + account.getEmailCheckToken() + "&email=" + account.getEmail(),
                account.getNickname(),
                "회원가입 인증",
                "제이크 스터디 서비스를 사용하려면 링크를 클릭하세요.",
                appProperties.getHost()
        );

        EmailMessage emailMessage = new EmailMessage(
                account.getEmail(),
                "회원가입 인증",
                mailText
        );

        emailService.sendEmail(emailMessage);
        ...

위에 만들어준 getMailHtmlText() 메소드를 통해 HTML을 구성하는 문자열을 받고, 이전에 추상화해둔 EmailMessage 객체에 해당 내용을 넣어주었다.

HtmlEmailService

...
mimeMessageHelper.setText(emailMessage.getText(), true);
...

.setText() 메소드의 2번째 인자는 HTML 사용 여부이다. HTML 문자열을 넣어주었으니 사용 여부를 true로 바꾸어주었다.

profile
풀스택 웹개발자로 일하고 있는 Jake Seo입니다. 주로 Jake Seo라는 닉네임을 많이 씁니다. 프론트엔드: Javascript, React 백엔드: Spring Framework에 관심이 있습니다.

0개의 댓글