package kr.wisestone.owl.monitor; import com.google.common.collect.Lists; import kr.wisestone.owl.util.WebAppUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import javax.mail.*; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeUtility; import javax.mail.search.FlagTerm; import java.io.*; import java.util.List; import java.util.Properties; /** * Created by jeong on 2018-02-08. */ public class MailMonitor { private static final Logger log = LoggerFactory.getLogger(MailMonitor.class); private volatile static MailMonitor uniqueInstance; private Store store; private String downloadDirectory = ""; private String userName = ""; private String password = ""; private MailMonitor() { // 시스템 프로퍼티를 읽어 다운로드 경로를 지정 this.initMailProperties(); this.connectEmail(); } public static MailMonitor getInstance() { if (uniqueInstance == null) { synchronized (MailMonitor.class) { if (uniqueInstance == null) { uniqueInstance = new MailMonitor(); } } } return uniqueInstance; } private void initMailProperties() { Properties properties = new Properties(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("system.properties"); try { properties.load(inputStream); this.downloadDirectory = properties.getProperty("mail.file.path"); this.userName = properties.getProperty("mail.account"); this.password = properties.getProperty("mail.password"); } catch (IOException e) { log.debug("initMailProperties() : " + e.getMessage()); } } private void connectEmail() { Properties properties = new Properties(); properties.setProperty("mail.host", "imap.gmail.com"); properties.setProperty("mail.port", "995"); properties.setProperty("mail.transport.protocol", "imaps"); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); try { this.store = session.getStore("imaps"); this.store.connect(); } catch (MessagingException e) { log.debug("connectEmail() : " + e.getMessage()); } } // TODO - 이메일 연동 시스템에서 추가적으로 사용자가 이메일을 보내고 싶은 프로젝트를 선택하는 설정 화면 개발이 필요하다. public List readMails() { Folder inbox = null; List emails = Lists.newArrayList(); try { inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); Message messages[] = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); System.out.println("Number of mails = " + messages.length); for (Message message : messages) { Email email = new Email(); Address[] from = message.getFrom(); /*System.out.println("-------------------------------"); System.out.println("Date : " + message.getSentDate()); System.out.println("From : " + MimeUtility.decodeText(from[0].toString())); System.out.println("Subject: " + MimeUtility.decodeText(message.getSubject())); System.out.println("Content :");*/ String contentType = message.getContentType(); String messageContent = ""; List emailAttachments = Lists.newArrayList(); if (contentType.contains("multipart")) { Multipart multiPart = (Multipart) message.getContent(); int numberOfParts = multiPart.getCount(); for (int partCount = 0; partCount < numberOfParts; partCount++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { // 첨부 파일 String fileName = MimeUtility.decodeText(part.getFileName()); EmailAttachment emailAttachment = new EmailAttachment(); emailAttachment.setName(fileName); emailAttachment.setPath(this.downloadDirectory + fileName); emailAttachments.add(emailAttachment); part.saveFile(this.downloadDirectory + fileName); } else { // 본문 텍스트 messageContent = this.getText(part); } } } else if (contentType.contains("text/plain") || contentType.contains("text/html")) { Object content = message.getContent(); if (content != null) { // 본문 텍스트 messageContent = content.toString(); } } /*System.out.println("\t Message: " + messageContent); System.out.println("--------------------------------");*/ email.setSubject(message.getSubject()); email.setFrom(MimeUtility.decodeText(from[0].toString())); email.setBody(messageContent); email.setAttachments(emailAttachments); emails.add(email); } //inbox.setFlags(messages, new Flags(Flags.Flag.SEEN), true); /*inbox.close(true); this.store.close();*/ } catch (NoSuchProviderException e) { log.debug("readMails() : "+ e.getMessage()); e.printStackTrace(); } catch (MessagingException e) { log.debug("readMails() : "+ e.getMessage()); e.printStackTrace(); } catch (UnsupportedEncodingException e) { log.debug("readMails() : "+ e.getMessage()); e.printStackTrace(); } catch (IOException e) { log.debug("readMails() : "+ e.getMessage()); e.printStackTrace(); } finally{ this.closeFolder(inbox); } return emails; } private String getText(Part part) throws MessagingException, IOException { if (part.isMimeType("text/*")) { return (String) part.getContent(); } if (part.isMimeType("multipart/alternative")) { // prefer html text over plain text Multipart mp = (Multipart) part.getContent(); String text = null; for (int i = 0; i < mp.getCount(); i++) { Part bp = mp.getBodyPart(i); if (bp.isMimeType("text/plain")) { if (text == null) { text = this.getText(bp); } continue; } else if (bp.isMimeType("text/html")) { String content = this.getText(bp); if (content != null) { return content; } } else { return this.getText(bp); } } return text; } else if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { String content = this.getText(mp.getBodyPart(i)); if (content != null) { return content; } } } return null; } private void closeFolder(Folder inbox) { try { if (inbox != null) { inbox.close(false); } } catch (MessagingException e) { log.debug("closeFolder() : "+ e.getMessage()); } } }