티스토리 뷰

Spring Framework 에서는 메일 발송 기능을 Gmail 과 Maven 을 통해 간편하게 사용할 수 있다.

아래와 같은 설정을 통해 이를 사용해보자.


pom.xml 에 dependency 추가

  <dependency>
       <groupId>javax.mail</groupId >
       <artifactId>mail</artifactId >
       <version>1.4</version >
  </dependency>


context.xml 에 Bean 등록

<bean id="mailSender" class = "org.springframework.mail.javamail.JavaMailSenderImpl">
     <property name= "host" value = "smtp.gmail.com"/>
     <property name= "port" value = "587"/>
     <property name= "defaultEncoding" value = "utf-8"/>
     <property name= "username" value = "userID@gmail.com"/>
     <property name= "password" value = "Password"/>
     <property name= "javaMailProperties">
          <props>
               <prop key= "mail.smtp.starttls.enable">true</prop>
               <prop key= "mail.smtp.auth" >true</prop>
          </props>
     </property>
</bean>

Property 의 username 에는 E-mail을 발송 할 계정의 주소를 password 에는 해당 계정의 비밀번호를 value 로 등록한다.



Email 객체가 될 Class 생성

public class Email {
    private String subject;
    private String content;
    private String regdate;
    private String reciver;
}

※ Generate Getters and Setters (Alt + Shite + S) 를 사용하여 Getter 와 Setter 를 생성 해주거나, 

    private 속성을 public 으로 변경하여 사용 해야한다.



Mail 을 보내줄 Sender Class 생성

@Component
public class EmailSender {
       
    @Autowired
    protected JavaMailSender mailSender;
 
    public void SendEmail(Email email) throws Exception {
        MimeMessage msg = mailSender.createMimeMessage();

        msg.setSubject(email.getSubject());
        msg.setText(email.getContent());
        msg.setRecipient(RecipientType.TO, new InternetAddress(email.getReciver()));
        
        mailSender.send(msg);
    }
}


Ex) 사용방법

@Autowired
private EmailSender emailSender;

Email email = new Email();
                   
email.setReciver("받는 주소");
email.setSubject("메일 제목");
email.setContent("메일 내용");
                     
emailSender.SendEmail(email);

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
글 보관함
«   2024/05   »
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 29 30 31