Spring Boot + Thymeleaf로 이메일 폼 관리 및 SMTP 메일 발송하기

1. 프로젝트 환경 설정

build.gradle 파일에 아래 의존성을 추가합니다

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}
dependencies { implementation 'org.springframework.boot:spring-boot-starter-mail' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' }
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

pom.xml을 사용하는 경우

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>

2. SMTP 설정

application.properties 또는 application.yml 파일에 이메일 발송을 위한 SMTP 설정을 추가합니다:

application.properties

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your_email@example.com
spring.mail.password=your_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=your_email@example.com spring.mail.password=your_password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your_email@example.com
spring.mail.password=your_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

application.yml

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
spring:
mail:
host: smtp.example.com
port: 587
username: your_email@example.com
password: your_password
properties:
mail:
smtp:
auth: true
starttls:
enable: true
spring: mail: host: smtp.example.com port: 587 username: your_email@example.com password: your_password properties: mail: smtp: auth: true starttls: enable: true
spring:
  mail:
    host: smtp.example.com
    port: 587
    username: your_email@example.com
    password: your_password
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true

3. thymeleaf 템플릿 생성

src/main/resources/templates/email 디렉토리에 이메일 템플릿 파일을 생성합니다.

email-template.html

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Email Template</title>
</head>
<body>
<h1 th:text="${subject}"></h1>
<p th:text="${content}"></p>
<p>Thank you,<br/>Spring Boot Mailer</p>
</body>
</html>
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Email Template</title> </head> <body> <h1 th:text="${subject}"></h1> <p th:text="${content}"></p> <p>Thank you,<br/>Spring Boot Mailer</p> </body> </html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Email Template</title>
</head>
<body>
    <h1 th:text="${subject}"></h1>
    <p th:text="${content}"></p>
    <p>Thank you,<br/>Spring Boot Mailer</p>
</body>
</html>

4. 이메일 서비스 구현

EmailService 클래스를 생성하여 이메일 발송 로직을 구현합니다.

EmailService.java

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.util.Map;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
public void sendEmail(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo(to);
helper.setSubject(subject);
// Thymeleaf 템플릿 처리
Context context = new Context();
context.setVariable("subject", subject);
context.setVariable("content", content);
String html = templateEngine.process("email/email-template", context);
helper.setText(html, true);
mailSender.send(message);
}
}
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import jakarta.mail.MessagingException; import jakarta.mail.internet.MimeMessage; import java.util.Map; @Service public class EmailService { @Autowired private JavaMailSender mailSender; @Autowired private TemplateEngine templateEngine; public void sendEmail(String to, String subject, String content) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(to); helper.setSubject(subject); // Thymeleaf 템플릿 처리 Context context = new Context(); context.setVariable("subject", subject); context.setVariable("content", content); String html = templateEngine.process("email/email-template", context); helper.setText(html, true); mailSender.send(message); } }
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.util.Map;

@Service
public class EmailService {

	@Autowired
	private JavaMailSender mailSender;

	@Autowired
	private TemplateEngine templateEngine;

	public void sendEmail(String to, String subject, String content) throws MessagingException {

		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message);

		helper.setTo(to);
		helper.setSubject(subject);

		// Thymeleaf 템플릿 처리
		Context context = new Context();
		context.setVariable("subject", subject);
		context.setVariable("content", content);

		String html = templateEngine.process("email/email-template", context);
		helper.setText(html, true);

		mailSender.send(message);
	}
}

5. 컨트롤러 및 서비스 호출

컨트롤러를 생성하여 이메일 발송 요청을 처리합니다:

EmailController.java

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import jakarta.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;
@RestController
public class EmailController {
@Autowired
private EmailService emailService;
@PostMapping("/send-email")
public String sendEmail(@RequestParam String to,
@RequestParam String subject,
@RequestParam String content) {
try {
emailService.sendEmail(to, subject, content);
return "Email sent successfully!";
} catch (MessagingException e) {
return "Failed to send email: " + e.getMessage();
}
}
}
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import jakarta.mail.MessagingException; import java.util.HashMap; import java.util.Map; @RestController public class EmailController { @Autowired private EmailService emailService; @PostMapping("/send-email") public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String content) { try { emailService.sendEmail(to, subject, content); return "Email sent successfully!"; } catch (MessagingException e) { return "Failed to send email: " + e.getMessage(); } } }
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class EmailController {

    @Autowired
    private EmailService emailService;

    @PostMapping("/send-email")
    public String sendEmail(@RequestParam String to,
                             @RequestParam String subject,
                             @RequestParam String content) {
        try {
            emailService.sendEmail(to, subject, content);
            return "Email sent successfully!";
        } catch (MessagingException e) {
            return "Failed to send email: " + e.getMessage();
        }
    }
}

6. 테스트

애플리케이션을 실행한 후, 아래와 같은 cURL 명령어로 이메일을 발송할 수 있습니다.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
curl -X POST \
-F "to=recipient@example.com" \
-F "subject=Hello from Spring Boot" \
-F "content=This is a test email using Thymeleaf." \
http://localhost:8080/send-email
curl -X POST \ -F "to=recipient@example.com" \ -F "subject=Hello from Spring Boot" \ -F "content=This is a test email using Thymeleaf." \ http://localhost:8080/send-email
curl -X POST \
  -F "to=recipient@example.com" \
  -F "subject=Hello from Spring Boot" \
  -F "content=This is a test email using Thymeleaf." \
  http://localhost:8080/send-email

성공적으로 이메일이 발송되었다면, 수신 이메일에서 템플릿이 적용된 HTML 이메일을 확인할 수 있습니다.

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 Akismet을 사용하여 스팸을 줄입니다. 댓글 데이터가 어떻게 처리되는지 알아보세요.