qordpsem 2024. 8. 12. 12:49

1. 기존 프로젝트에 메일 보내는 기능 추가

 

1-2. SpringConfig 파일 추가

package com.example.demo;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;

@Configuration
public class SpringConfig {
	@Bean
	public JavaMailSenderImpl javaMailSender() {
		JavaMailSenderImpl jms = new JavaMailSenderImpl();
		jms.setHost("smtp.gmail.com");
		jms.setPort(587);
		jms.setUsername("내 구글 아이디");
		jms.setPassword("내 구글 비밀번호 - 앱비밀번호 16자리");
		jms.setDefaultEncoding("UTF-8");
		
		Properties prop = new Properties();
		prop.put("mail.smtp.starttls.enable", true);
		prop.put("mail.smtp.auth", true);
		prop.put("mail.smtp.ssl.checkserveridentity", true);
		prop.put("mail.smtp.ssl.trust", "*");
		prop.put("mail.smtp.ssl.protocols", "TLSv1.2");
		
		jms.setJavaMailProperties(prop);
		
		return jms;
	}
}

 

1-3. MailController 파일 추가

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MailController {
	
	@Autowired
	private MailSender mailSender;

	@GetMapping("/mail")
	public void mail() {
		SimpleMailMessage mailMessage = new SimpleMailMessage();
		mailMessage.setSubject("중요한 문서");
		mailMessage.setFrom("내 아이디@gmail.com");
		mailMessage.setText("안녕안녕");
		mailMessage.setTo("상대 아이디@gmail.com");
		try {
			mailSender.send(mailMessage);
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}