자바메일을 사용하기 위한 준비 과정.
1.자바메일을 사용하기 위해 dependency 를 추가.
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>stringtemplate</artifactId>
<version>4.0.2</version>
</dependency>
2.프로젝트 내 mail 패키지 추가.
mail.host=smtp.gmail.com
mail.username=dlsdnd345@gmail.com
mail.password=qkr50715071
mail.protocol=smtps
mail.port=465
mail.fromAddress=dlsdnd345@gmail.com
mail.error.fromAddress=dlsdnd345@gmail.com
mail.error.receivers=dlsdnd345@naver.com;dlsdnd345@gmail.com;
mail.error.prefix=[BRMS]
mail.template.path=C:/Users/admin/Desktop/bookapplication08/src/test/resources
mail.template.error=errormail.template
4. configuration 설정
@PropertySource({"file:src/test/resources/mail.properties" })
5. MailSenderConfiguration 추가
@Configuration@ComponentScan(value = { "com.iw.mail" })
public class MailSenderConfiguration {
@Value("${mail.host}")
private String host;
@Value("${mail.username}")
private String username;
@Value("${mail.password}")
private String password;
@Value("${mail.port}")
private String portString;
@Value("${mail.protocol}")
private String protocol;
@Bean
public JavaMailSender javaMailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(host);
javaMailSender.setUsername(username);
javaMailSender.setPassword(password);
int port = Integer.parseInt(portString);
javaMailSender.setPort(port);
javaMailSender.setProtocol(protocol);
return javaMailSender;
}
}
6.error Templte 추가
<h3>ERROR 발생시간 : $time$</h3><table width="100%" bgcolor="#d1d9e4" cellspacing="1" cellpadding="3"><tr>
<td bgcolor="#666666" colspan="2"><font face="Arial" color="white"><b>$message$</b></font></td></tr><tr>
<td><font face="Arial" size="2">StackTraces</font></td>
<td><font face="Arial" size="2">$stackTraces$</font></td></tr>
자바메일 코드 이해
자바 메일 코드 순서
ErrorMailSenderImpl -> TemplateMailSenderImpl -> MailSenderImpl
ErrorMailSenderImpl
@Componentpublic class ErrorMailSenderImpl implements ErrorMailSender {
@Autowired
private TemplateMailSender templateMailSender;
private String[] receivers;
@Value("${mail.error.fromAddress}")
private String fromAddr; // 보내는사람 사람
@Value("${mail.template.path}")
private String templatePath; // error.Template 파일 위치
@Value("${mail.template.error}")
private String errorTemplate; // error.Template 파일 이름
@Value("${mail.error.prefix}")
private String prefix;
@Value("${mail.error.receivers}")
private String receiveresString; //받을 사람등
@PostConstruct
// 초기화 작업을 수행할 메서드에 적용 받을 사람들 파싱 작업
public void init() {
receivers = receiveresString.split(";");
}
@Override
public MimeMessagePreparator buildErrorMessage(Exception ex) throws IOException, MessagingException {
String templateFileName = templatePath + "/" + errorTemplate; // error.template 파일경로
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format(new Date());
String message = ex.getMessage();
StringBuilder sb = new StringBuilder();
for (StackTraceElement el : ex.getStackTrace()) {
sb.append(el.toString() + "<br/>");
}
Map<String, String> templateItems = new HashMap<>();
templateItems.put("time", time);
templateItems.put("message", message);
templateItems.put("stackTraces", sb.toString());
return templateMailSender.prepareMimeMessage(receivers, "서버 에러", templateFileName, templateItems,
fromAddr, "BRMS 관리자");
}
// 콜백 패턴 사용
@Override
public void send(Exception ex) {
try {
templateMailSender.send(buildErrorMessage(ex));
} catch (Exception mailSenderEx) {
System.err.println(mailSenderEx);
}
}
}
TemplateMailSenderImpl
@Componentpublic class MailSenderImpl implements MailSender {
@Autowired
private JavaMailSender javaMailSender;
@Override
public MimeMessagePreparator prepareMimeMessage(final String[] toAddresses, final String subject,
final String content, final String fromAddress, final String fromAddressName) {
return new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
for (String address : toAddresses) {
Address toAddr = new InternetAddress(address, fromAddressName);
mimeMessage.addRecipient(RecipientType.TO, toAddr);
}
Address fromAddr = new InternetAddress(fromAddress);
mimeMessage.setFrom(fromAddr);
mimeMessage.setSubject(subject, "UTF-8");
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart msgPart = new MimeBodyPart();
msgPart.setContent(content, "text/html;charset=utf-8");
multipart.addBodyPart(msgPart);
mimeMessage.setContent(multipart);
}
};
}
@Override
public boolean send(MimeMessagePreparator message) {
javaMailSender.send(message);
return true;
}
}
1.Controller Error 시 email 발송
@requestMapping 어노테이션에 매핑 작업을 하기 위해 aop 사용
aop 를 어노테이션으로 간편하게 사용하기 위한 dependency 추가
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
2.aop 파일 추가
@Aspect// aop 를 사용하기 위한 어노테이션@Componentpublic class RequestMappingErrorMailAdvice {
@Autowired(required = false)
private ErrorMailSender errorMailSender;
// 매핑 시킬 어노테이션
@Pointcut(value = "@annotation(org.springframework.web.bind.annotation.RequestMapping)")
private void requestMappingPointcut() {
}
//aop 내부 내용
@Around("requestMappingPointcut()")
public Object wrapResponseObject(ProceedingJoinPoint pjp) throws Throwable {
try {
Object ret = pjp.proceed();
System.out.println(ret);
return ret;
} catch (Exception ex) {
errorMailSender.send(ex);
throw ex;
}
}
}
3. EnableMailSender 추가
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(value = MailSenderConfiguration.class)
public @interface EnableMailSender {
}
4.DomainConfiguration 설정
@ComponentScan({"com.iw.aops" })
@EnableAspectJAutoProxy
@EnableMailSender
|