java/Spring
[Spring] 이메일 전송 구현(구글 이메일)
킨글
2025. 1. 26. 16:13
구글 앱 비밀번호 추가
생성된 앱 비밀번호 확인
gradle.build
dependencies {
...
implementation 'org.springframework.boot:spring-boot-starter-mail'
...
}
application.properties
spring.mail.host=smtp.gmail.com # 이메일 gmail로 사용
spring.mail.port=587
spring.mail.username=your-email@naver.com
spring.mail.password=여기에_앱 비밀번호_입력
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Controller
package com.travel.api.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.travel.api.service.EmailService;
@RestController
public class EmailController {
private final EmailService emailService;
@Autowired
public EmailController(EmailService emailService) {
this.emailService = emailService;
}
@GetMapping("/email/send")
public String sendEmail() {
emailService.sendEmail("to@naver.com", "테스트 이메일", "테스트 내용");
return "ok";
}
}
Service
package com.travel.api.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
private final JavaMailSender mailSender;
@Autowired
public EmailService(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendEmail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
}