티스토리 뷰

* Spring 3 환경에서 메일을 발송하는 방법을 조사해봤다. 간단하게 Oracle에서 제공하는 JavaMail API를 사용하면 된다. 현재 최신 버전은 1.4.7이며 maven javamail로 구글링하면 mail-1.4.7.jar 파일을 다운로드받을 수 있다.


* 다운로드받은 mail-1.4.7.jar 파일을 프로젝트의 CLASSPATH에 추가한다. 웹 애플리케이션의 경우 /WebContent/WEB-INF/lib 디렉토리에 복사하면 간단하게 끝난다.


* 메일 발송 정보를 저장할 mail.xml 파일을 작성한다.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bean="http://www.springframework.org/schema/bean"

xsi:schemaLocation="

        http://www.springframework.org/schema/beans 

        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

<bean id="mailSender"

class="org.springframework.mail.javamail.JavaMailSenderImpl">

<property name="host" value="smtp.somemailhost.com" />

<property name="port" value="25" />

<property name="username" value="someuser" />

<property name="password" value="somepassword" />

<prop key="mail.transport.protocol">smtp</prop>

<prop key="mail.smtp.auth">true</prop>

<prop key="mail.smtp.starttls.enable">true</prop>

<prop key="mail.debug">true</prop>

</property>

</bean>

</beans>


* DispatcherServlet 역할을 하는 XML 파일에 아래 내용을 추가한다.

<import resource="mail.xml" />


* 애플리케이션의 @Service 오브젝트에서 사용될 MailService 클래스를 작성한다. 아래는 간단한 예로 첨부 파일 발송, HTML 템플릿 등을 적용하려면 살을 더 붙여야 한다.

@Service("mailService")

public class MailService {

  @Autowired

  private MailSender mailSender;

  

  public void sendMail(String from, String to, String subject, String text) {

    SimpleMailMessage message = new SimpleMailMessage();

    message.setFrom(from);

    message.setTo(to);

    messate.setSubject(subject);

    message.setText(text);

    mailSender.send(message);

  }  

}


* 메일 발송 비즈니스 로직을 수행할 @Service 클래스에서는 아래와 같이 작성한다.

@Service("someService")

public class someService {

  @Autowired

  private MailService mailService;

  

  public void sendMail() {

    mailService.sendMail("from@MailAddress.com", "to@MailAddress.com", "someSubject", "someText");

  }

}


<참고자료>

Send Mail with Spring : JavaMailSenderImpl Example (by Lokesh Gupta)

http://howtodoinjava.com/2013/05/27/send-email-with-spring-javamailsenderimpl-example/


Spring Framework 3.2 Reference Documentation: 26. Email

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mail.html


댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
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
글 보관함