[java] Thymeleaf를 사용하여 이메일 템플릿을 어떻게 만들 수 있나요?

Thymeleaf는 Java 기반의 템플릿 엔진으로, HTML을 생성하고 렌더링하는 데 사용됩니다. 이메일 템플릿을 만들기 위해 Thymeleaf를 사용하려면 다음 단계를 따르면 됩니다:

  1. Thymeleaf 종속성 추가: Maven이나 Gradle과 같은 빌드 도구를 사용하여 프로젝트에 Thymeleaf 종속성을 추가해야 합니다. 아래는 Maven을 사용하는 경우의 예시입니다:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 이메일 템플릿 만들기: 이메일 템플릿은 일반적으로 html 확장자를 가진 파일로 작성됩니다. 사용자 지정 템플릿 폴더를 만들고, 예를 들어 email-templates 폴더를 생성합니다. 그리고 그 안에 welcome.html 파일을 생성합니다. 템플릿 파일 안에는 Thymeleaf 템플릿 문법을 사용하여 HTML 코드를 작성할 수 있습니다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Welcome Email</title>
</head>
<body>
    <h2>Welcome, <span th:text="${username}"></span>!</h2>
    <p>Thank you for joining our platform.</p>
</body>
</html>
  1. 이메일 전송 서비스 준비하기: 이메일 서비스를 구현하기 위해 JavaMail이나 Spring Mail과 같은 라이브러리를 사용할 수 있습니다.

  2. 템플릿 렌더링하기: 이제 템플릿을 렌더링하고 이메일로 전송하기 위해 다음 코드를 사용할 수 있습니다.

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

// ...

@Autowired
private JavaMailSender emailSender;

@Autowired
private TemplateEngine templateEngine;

public void sendWelcomeEmail(String recipientEmail, String username) throws MessagingException {
    // 이메일 템플릿 렌더링을 위해 Thymeleaf 컨텍스트 생성
    Context thymeleafContext = new Context();
    thymeleafContext.setVariable("username", username);

    // 템플릿을 Thymeleaf 엔진을 사용하여 렌더링
    String htmlBody = templateEngine.process("email-templates/welcome", thymeleafContext);

    // MimeMessage 생성
    MimeMessage message = emailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(recipientEmail);
    helper.setSubject("Welcome to our platform");
    helper.setText(htmlBody, true);

    // 이메일 전송
    emailSender.send(message);
}

위의 코드는 Spring Framework를 기반으로 작성되었지만, Spring을 사용하지 않는 경우에도 Thymeleaf 템플릿 엔진을 사용하는 방법은 동일합니다. 이제 sendWelcomeEmail 메서드를 호출하여 실제로 이메일을 전송할 수 있습니다.

참고 문서: