Akashic Records

Spring Boot Mail Starter 본문

Spring.io

Spring Boot Mail Starter

Andrew's Akashic Records 2023. 4. 25. 17:22
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
Comments