728x90
Gradle을 사용하는 경우와 최신 스타일 코딩을 적용한 이메일 발송 프로그램 예제입니다.
1. `build.gradle` 파일에 `spring-boot-starter-mail` 의존성을 추가합니다.
dependencies {
// ...
implementation 'org.springframework.boot:spring-boot-starter-mail'
// ...
}
2. `application.yml` 파일에 메일 발송 관련 설정을 추가합니다.
spring:
mail:
host: smtp.example.com
port: 587
username: your_email@example.com
password: your_email_password
properties:
mail:
smtp:
auth: true
starttls:
enable: true
3. 메일 발송을 처리하는 `EmailService` 클래스를 작성합니다.
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.nio.file.Path;
@Service
public class EmailService {
private final JavaMailSender mailSender;
public EmailService(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendEmailWithAttachment(String to, String subject, String text, Path attachmentPath) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
// 파일 첨부
helper.addAttachment(attachmentPath.getFileName().toString(), attachmentPath.toFile());
mailSender.send(message);
}
}
4. 이제 `EmailService`를 사용하여 이메일을 발송할 수 있는 `EmailController`를 작성합니다.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.nio.file.Paths;
@RestController
public class EmailController {
private final EmailService emailService;
public EmailController(EmailService emailService) {
this.emailService = emailService;
}
@GetMapping("/send-email")
public String sendEmail() {
String to = "recipient@example.com";
String subject = "Test Email with Attachment";
String text = "Hello! This is a test email with an attachment.";
String attachmentPath = "/path/to/your/attachment.file";
try {
emailService.sendEmailWithAttachment(to, subject, text, Paths.get(attachmentPath));
return "Email sent successfully!";
} catch (Exception e) {
return "Error sending email: " + e.getMessage();
}
}
}
이제 `/send-email` 엔드포인트를 호출하면 설정된 수신자에게 첨부 파일이 포함된 이메일이 전송됩니다.
728x90
'Spring.io' 카테고리의 다른 글
Spring framework 개발 Tip (0) | 2023.05.11 |
---|---|
Spring Batch Tasklet 단위 테스트(Unit Test) (0) | 2023.04.27 |
How to run Spring Boot application unpack-jar (0) | 2023.04.25 |
Spring Batch, Excel ItemReader로 읽어서 JPA ItemWriter 쓰기 (0) | 2023.04.21 |
Spring Batch DataBase 설정 (0) | 2023.04.21 |