OWL ITS + 탐지시스템(인터넷 진흥원)
이민희
2022-01-13 4545664bbece1b1b185945376b344b1660669a53
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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<Email> readMails() {
        Folder inbox = null;
        List<Email> 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<EmailAttachment> 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());
        }
    }
}