hanker

Spring Boot - 이메일 전송(1)(JavaMailSender) 본문

SPRING

Spring Boot - 이메일 전송(1)(JavaMailSender)

hanker 2021. 10. 4. 15:05
반응형

Spring Boot 이메일 전송

 

1. pom.xml 의존성 주입 

        <!-- Email 인증 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

- JavaMailSender 등 클래스, 인터페이스를 사용하기 위함

 

 

2. resources 경로 밑에 mail/email.properties 파일 생성 (gmail SMTP 사용)

## Email Settings
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=Gmail아이디@gmail.com
spring.mail.password=Gmail비밀번호
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

spring.mail.transport.protocol=smtp
spring.mail.debug=true
spring.mail.default.encoding=UTF-8

 

 

3. EmailConfig 설정

@Configuration
@PropertySource("classpath:mail/email.properties")
public class EmailConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public EmailConfig() throws IOException {
        logger.info("EmailConfig.java constructor called");
    }

    @Value("${spring.mail.transport.protocol}")
    private String protocol;

    @Value("${spring.mail.properties.mail.smtp.auth}")
    private boolean auth;

    @Value("${spring.mail.properties.mail.smtp.starttls.enable}")
    private boolean starttls;

    @Value("${spring.mail.debug}")
    private boolean debug;

    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.port}")
    private int port;

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;

    @Value("${spring.mail.default.encoding}")
    private String encoding;


    @Bean
    public JavaMailSender javaMailSender(){
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", protocol);
        properties.put("mail.smtp.auth", auth);
        properties.put("mail.smtp.starttls.enable", starttls);
        properties.put("mail.smtp.debug", debug);

        mailSender.setHost(host);
        mailSender.setUsername(username);
        mailSender.setPassword(password);
        mailSender.setPort(port);
        mailSender.setJavaMailProperties(properties);
        mailSender.setDefaultEncoding(encoding);

        return mailSender;
    }
}

 

4. View 설정

<div class="form-floating mb-3">
  <input class="form-control" id="inputEmail" type="email" />
  <label for="inputEmail" th:text="#{email}"></label>
  <button class="btn btn-secondary btn-block" th:text="#{certified_email}"
  id="certEmail">
  </button>
</div>
$(function(){
  $("#certEmail").click(function(){
      var data = {
          email : $("#inputEmail").val(),
      };

      $.ajax({
          url : "/certifiedEmail",
          type : "post",
          data : data,
          dataType : "json",
          success: [function(rs){
              console.log(rs);
          }], error : function(rs){           
          }
     });
  });
});

- 이메일을 입력하여 message를 보내는 방식

 

 

5. Controller

@PostMapping("/certifiedEmail")
public void certifiedEmail(@RequestParam("email") String email){

    loginService.mailSend(email);

}

 

 

6. Service

private final JavaMailSender javaMailSender;

public void mailSend(String email) {
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    simpleMailMessage.setTo(email);
    simpleMailMessage.setSubject("title");
    simpleMailMessage.setText("Text Mail Sender");

    javaMailSender.send(simpleMailMessage);
}

- setSubject : 제목

- setText : 글내용

 

 

결과

반응형