JCF3.0™ 메일링 적용 가이드

From JCFWiKi

Jump to: navigation, search

그림:check.gif

  • 산출물 : JCF3.0™ 메일링 적용 가이드
  • 작성자: 송희정
  • 작성일 : 2007/12/07

Copyright © 2007 Daewoo Information Systems Co., Ltd.

목차

[편집] 개 요

[편집] 메일 발송 모듈

프로젝트 내에서 메일링 리스트에 대한 메일 발송이나, 요청사항 처리내역에 대한 메일로 알려주는 기능을 구현하기 위해서는 메일 발송 기능이 필요하게 된다. 기존에는 각기 다른 형태로 메일 발송을 처리하던 것을 프레임웍 기반으로 하여 쉽고 간단하게 메일을 발송할 수 있도록 한다.

[편집] JCF 3.0에서의 개선점

  • 메일 발송시 파일 첨부 기능
    • JCF2.0 Mailer에는 존재하지 않아서 메소드 추가함
    • 여러 파일을 첨부할 수 있으므로, File[]로 받음
    • 한글명의 파일을 첨부할 경우, 파일명이 깨지는 현상때문에 new String(attachFiles[i].getName().getBytes(),"8859_1") 로 처리


[편집] 예제 다운 받기

  • 형상관리 서버를 통해 메일 발송 관련 예제를 다운 받도록 한다.
    • 프로젝트 명 : jcf3.0-samples-mail
  • 설명
    • 이 예제 프로젝트는 주로 사용될 세가지 경우에 대한 메일 발송 예제 클래스가 있으며, 기본적인 설정을 위한 app.properties, applicationContext.xml 이 있다.
    • 메일 발송에 필요한 라이브러리들은 Maven을 통해 관리될 것이다.

그림:jcf3_mail_project.JPG


[편집] 환경설정

[편집] app.properties

  • 메일발송을 위한 정보를 properties에 입력한다.
  • mail.host : SMTP서버명
  • mail.from, mail.to : 발신, 수신 메일 주소를 지정하지 않을 경우 기본 값
  • input.encoding, output.encoding : vm 파일 처리시 한글 깨짐을 방지하기 위해 설정함. (EUC-KR/UTF-8)
# Mail 
mail.host disc.co.kr
mail.from admin@samples.org
mail.to
mail.charset EUC-KR
 
# Velocity(Template Engine)
input.encoding UTF-8
output.encoding UTF-8
parser.pool.size 100
file.resource.loader.path xdocs/stylesheets

[편집] applicationContext 설정

<!-- Velocity Support -->
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
	<property name="velocityProperties">
	<props>
		<prop key="resource.loader">class</prop>
		<prop key="class.resource.loader.class">
			org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
		</prop>          
		<prop key="input.encoding">${input.encoding}</prop>              
		<prop key="output.encoding">${output.encoding}</prop>     
		<prop key="parser.pool.size">${parser.pool.size}</prop>  
	</props>
	</property>    
</bean>
 
<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
	<property name="from">
		<value><![CDATA[Samples Application <admin@samples.com>]]></value>
	</property>
	<property name="subject">Your application has been received</property>
</bean>
 
<!-- MailSender used by EmailAdvice -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="host"><value>${mail.host}</value></property>
</bean>
 
<!-- Lists the images in the image database and sends a corresponding mail -->
<bean id="mailer" class="jcf.mail.Mailer">
	<property name="mailSender"><ref bean="mailSender"/></property>
	<property name="message"><ref bean="mailMessage"/></property>
	<property name="velocityEngine"><ref bean="velocityEngine"/></property>
	<property name="mailCharset"><value>${mail.charset}</value></property>
</bean>
  • 테스트 소스는 편의상 다음의 설정을 상수로 선언하여 사용한다.
private String from = "hjsong@disc.co.kr";
private String to = "mariaro@naver.com";
private String subject = "JCF Mailer Test! (SimpleMessage)";
private String content = "Thanks for your support!";	
private String template = "templates/mailTemplate.vm";
private String userName ="송희정";

[편집] 단순 메일 발송 : SimpleMailerTest

  • 메일 수신/발신자와 제목, 간단한 내용만 보내는 경우 사용
  • jcf.module.mail.Mailer의 sendMail 메소드를 이용
public void testSimpleMessage() {
mailer.sendMail(from, to,
"JCF Mailer Test! (SimpleMessage)", "Thanks for your support!");
}

  public void testMimeMessage() {   try { MimeMessage message = mailer.getMailSender().createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setFrom(from); helper.setSubject("JCF Mailer Test! (MimeMessage)"); helper.setText("Thanks for your support!");

mailer.getMailSender().send(message);
} catch (MessagingException e) {

e.printStackTrace(); }

}

[편집] 템플릿을 이용한 메일 발송 : TemplateMailerTest

[편집] 템플릿

  • 공통적으로 화면 형태를 재활용 할 필요가 있는 경우, 템플릿으로 JSP나 vm 파일을 만들어 두고 사용할 수 있다.
  • 아래 예제는 vm 파일을 사용하여 src 경로에 두고, 자바 클래스처럼 처리하면 된다.
  • 템플릿에서 변수 부분은 ${변수명} 으로 처리하면 변수값으로 replace 되어 메일이 발송된다.
<B>${userName}님! 반갑습니다.</B><br/>
<br/> 메일 테스트 입니다. <font color=blue> 아래 링크로 웹사이트를 둘러보십시오.<br/> 좋은 서비스를 제공하기 위해서 항상 노력하겠습니다.<br/> <br/> <a href="http://wiki.dev.daewoobrenic.co.kr">JCF 사이트 둘러보기</a> </font><br/> <br/>

[편집] 자바소스

  • sendTemplateMail이라는 메소드를 이용하며 template 파일의 경로를 함께 넘겨주도록 한다.
  • vm 파일에서의 변수는 HashMap으로 담아서 넘겨준다. 이 때 vm에서 지정한 변수명이 Map에서의 키가 되도록 주의한다.
public void testSimpleMessage() {
private String template = "templates/mailTemplate.vm";
HashMap model = new HashMap();

model.put("userName", userName);

mailer.sendTemplateMail(from, to, subject, model, template);
}


[편집] JUnit으로 테스트하기

  • Eclipse에서 Junit을 이용하여 테스트 하게 되면 그 결과를 Junit view에서 확인할 수 있다.
  • 성공한 경우 초록색으로 마크가 되며, 실패한 경우 빨간색으로 마크가 된다.

그림:jcf3_mail_junit.JPG


[편집] 메일 확인하기

  • 메일로 온 결과를 보면 vm 파일에 있던 내용에서 ${}로 되어 있던 부분이 변수값으로 대체되어 온 것을 볼 수 있다.

그림:jcf3_mail_template.JPG

[편집] 첨부파일이 있는 메일 발송 : AttachMailerTest

  • sendMailWithAttachments 메소드를 이용한다.
  • 첨부 파일의 경우 파일을 여러개 첨부할 수 있으므로, File[]을 이용하여 넘겨준다.
public void testMimeMessageWithFileAttachment() {
 
  File[] attachment;
    try {
      File file = new File(fileName);
      attachment = new File[] { file };
mailer.sendMailWithAttachments(from, to, subject, content, attachment);
} catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (MessagingException e) {
     e.printStackTrace();
   }
}