Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- express
- spread 연산자
- Unity IAP
- Camera Zoom
- Camera Movement
- draganddrop
- critical rendering path
- mongoDB
- Spring Boot
- linux
- OverTheWire
- java
- Digital Ocean
- Unity Editor
- Git
- springboot
- screencapture
- server
- MySQL
- --watch
- rpg server
- react
- css framework
- SDK upgrade
- unity
- Google Developer API
- docker
- nodejs
- Google Refund
- Packet Network
Archives
- Today
- Total
우당탕탕 개발일지
[SpringBoot] 네이버 메일 전송하기 본문
고객이 문의하기를 남기면 문의하기 내용과 함께 이메일로 전송이 되는 기능을 구현하고 있다. 구글은 많이 복잡하다고 하여, 오늘은 네이버로 구현해본다. 다음에 기회가 되면 구글로도 구현해보자. ( 사실은 구글 구현하다가 계속 인증실패가 떠서 중도포기했다.. 다음번에 꼭 정복해보도록 하자..ㅜㅜㅜ)
네이버 계정에서 SMTP 를 활성화
네이버 메일에 로그인 > 환경설정 > IMAP / SMTP 설정 > 외부메일 프로그램 사용 옵션을 활성화한다.
네이버 계정 설정 > 보안설정 > 2단계 인증 > 애플리케이션 비밀번호를 생성한다. 종류는 지메일로 하였다. 비밀번호는 한번 페이지를 벗어나면 다시 보여주지 않으므로 다른곳에 잘 백업해 두도록 하자.
SpringBoot 프로젝트에 dependencies 추가
build.gradle 의 dependencies 블록에 다음 2개를 추가해준다.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'jakarta.mail:jakarta.mail-api:2.0.1'
}
application.properties 작성
아까 네이버 설정에서 생성한 애플리케이션 비밀번호를 your_app_password 자리에 넣어준다.
spring.mail.host=smtp.naver.com
spring.mail.port=587
spring.mail.username=your_email@naver.com
spring.mail.password=your_app_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
메일 전송 코드 작성
호출부 ContactController.java
import java.io.Console;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.esa.hompage_server.dto.ContactRequest;
import com.esa.hompage_server.service.ContactService;
import com.fasterxml.jackson.databind.ObjectMapper;
@RestController
@RequestMapping("/api")
public class ContactController {
@Autowired
private ContactService contactService;
@PostMapping("/contact")
public String handleFormSubmission(@RequestBody ContactRequest form) {
try {
// 1. 객체를 문자열로 변환 (JSON 포맷)
ObjectMapper objectMapper = new ObjectMapper();
String objectAsString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(form);
// 2. 이메일 전송
contactService.sendEmail(
"to-email@example.com", // 수신자 이메일
"객체 전송 결과", // 메일 제목
"다음은 전달받은 객체의 문자열화 결과입니다:\n\n" + objectAsString // 메일 본문
);
return "이메일 전송 성공!";
} catch (Exception e) {
e.printStackTrace();
return "이메일 전송 실패: " + e.getMessage();
}
}
}
구현부 ContactService.java
package com.esa.hompage_server.service;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
@Service
public class ContactService {
private final JavaMailSender mailSender;
public ContactService(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendEmail(String to, String subject, String body) throws MessagingException {
// MimeMessage 객체 생성
MimeMessage message = mailSender.createMimeMessage();
// Helper를 사용해 메시지 구성
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom("from-email@example.com"); // 발신자 이메일 주소
helper.setTo(to); // 수신자 이메일 주소
helper.setSubject(subject); // 이메일 제목
helper.setText(body, true); // 이메일 본문 (HTML 허용)
// 이메일 전송
mailSender.send(message);
System.out.println("Email sent successfully!");
}
}
네이버는 비교적으로 간단하다.
외국에서는 네이버를 잘 사용하지 않기 때문에, 국내이용자만 있을 경우에 사용하는 것이 적합하다.
외국 이용자가 많을 경우 구글을 사용하자.
'Server' 카테고리의 다른 글
[nestJs] 파일 다운로드 시 서버가 재실행되는 문제 (feat. --watch) (0) | 2025.01.17 |
---|---|
[SpringBoot] 민감한 데이터 .env 에 보관/사용하기 (0) | 2025.01.12 |
[SpringBoot] 7. 스프링부트 배포하기(완) (0) | 2025.01.10 |
[SpringBoot] 6. 데이터베이스의 객체와 연관관계 (Repository 계층) (1) | 2025.01.08 |
[SpringBoot] 5. 트랜잭션 (Service 계층) (0) | 2025.01.06 |