[测评系统]--测评系统核心代码库
林致杰
2021-12-03 ce080c08f08c01695ddc9d9510b77eb6d2c7a38d
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
package com.ots.project.tool.email.utils;
import lombok.extern.slf4j.Slf4j;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
 
@Slf4j
public class EmailUtil {
    private String username = null; 
    private String password = null; 
    
    public EmailUtil(String username, String password) {
        this.username = username;
        this.password = password;
    }
    
    public static boolean isSeen(MimeMessage msg) throws MessagingException {
        return msg.getFlags().contains(Flags.Flag.SEEN);
    }
    
    public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
        StringBuffer receiveAddress = new StringBuffer();
        Address[] addresss = null;
        if (type == null) {
            addresss = msg.getAllRecipients();
        } else {
            addresss = msg.getRecipients(type);
        }
        if (addresss == null || addresss.length < 1)
            throw new MessagingException("没有收件人!");
        for (Address address : addresss) {
            InternetAddress internetAddress = (InternetAddress) address;
            receiveAddress.append(internetAddress.toUnicodeString()).append(",");
        }
        receiveAddress.deleteCharAt(receiveAddress.length() - 1); 
        return receiveAddress.toString();
    }
    
    public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
        
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part) part.getContent(), content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart, content);
            }
        }
    }
    
    public Session createSession(Properties props) {
        Session session = Session.getInstance(props, new Authenticator() {
 
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                PasswordAuthentication pa = new PasswordAuthentication(username, password);
                return pa;
            }
        });
        return session;
    }
    
    public void sendMail(Properties props, SendEmailMessage sem) throws Exception {
        Session session = createSession(props);
        
        Message msg = new MimeMessage(session);
        msg.setFrom(InternetAddress.parse(MimeUtility.decodeText(sem.getFrom()))[0]);
        
        msg.setRecipients(RecipientType.TO, InternetAddress.parse(sem.getRecipient()));
        msg.setSubject(sem.getSubject());
        msg.setText(sem.getText());
        msg.setSentDate(new Date());
        
        Transport.send(msg);
    }
    
    public List<BouncedUser> receiveMail(Properties props, String protocol) {
        Store store = null;
        List<BouncedUser> bouncedUserList = new ArrayList<>();
        try {
            Session session = createSession(props);
            store = session.getStore(protocol);
            store.connect(); 
            Folder inbox = store.getFolder("INBOX"); 
            inbox.open(Folder.READ_WRITE); 
            FetchProfile profile = new FetchProfile();
            profile.add(FetchProfile.Item.ENVELOPE); 
            Message[] msgs = inbox.getMessages(); 
            inbox.fetch(msgs, profile); 
            for (int i = 0; i < msgs.length; i++) {
                MimeMessage msg = (MimeMessage) msgs[i];
                String sender = decodeText(msgs[i].getFrom()[0].toString());
                if (isSeen(msg)) { 
                    continue;
                }
                if (countStr(sender, "PostMaster") > 0) {
                    StringBuffer content = new StringBuffer(30);
                    getMailTextContent(msg, content);
                    String head = "收件人(";
                    int start = content.indexOf(head);
                    int end = content.indexOf(")", start);
                    String realSender = content.substring(start + head.length(), end);
                    String message = content.substring(end, end + 30);
                    BouncedUser bouncedUser = new BouncedUser();
                    bouncedUser.setRealsender(realSender);
                    bouncedUser.setSentDateExtend(getSentDate(msg, "yyyy-MM-dd HH:mm:ss"));
                    bouncedUser.setReason(message);
                    int len = content.length();
                    if (len > 3000) {
                        len = 3000;
                    }
                    bouncedUser.setContent(content.toString().substring(0, len));
                    bouncedUser.setTitle(msgs[i].getSubject());
                    bouncedUser.setReceiveaddress(getReceiveAddress(msg, null));
                    bouncedUser.setSenddate(msg.getSentDate());
                    bouncedUser.setSender(sender);
                    bouncedUserList.add(bouncedUser);
                    log.error("----------------------------------------------------------------------");
                    log.error("发送时间:{}", msgs[i].getSentDate());
                    log.error("发送时间:{}", getSentDate(msg, "yyyy-MM-dd HH:mm:ss"));
                    log.error("发送人:{}", sender);
                    log.error("收件人:{}", getReceiveAddress(msg, null));
                    log.error("大小:{}", msgs[i].getSize());
                    log.error("是否已读:{}", isSeen(msg));
                    log.error("标题:{}", msgs[i].getSubject());
                    log.error("内容:{}", msgs[i].getContent());
                    log.error("退信邮箱地址:{}", realSender);
                    log.error("退信原因:{}", message);
                    log.error("----------------------------------------------------------------------");
                }
            }
        } catch (Exception ex) {
            log.error("接收邮件拉取失败:{}" + ex.getMessage(), ex);
        } finally {
            if (Objects.isNull(store)) {
                try {
                    store.close();
                } catch (MessagingException e) {
                    log.error("关闭邮箱拉取连接通道失败:{}", e.getMessage(), e);
                }
            }
        }
        return bouncedUserList;
    }
    
    private int countStr(String str, String sToFind) {
        int num = 0;
        while (str.contains(sToFind)) {
            str = str.substring(str.indexOf(sToFind) + sToFind.length());
            num++;
        }
        return num;
    }
    
    public String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
        Date receivedDate = msg.getSentDate();
        if (receivedDate == null)
            return "";
        if (pattern == null || "".equals(pattern))
            pattern = "yyyy年MM月dd日 E HH:mm ";
        Calendar cal = Calendar.getInstance();
        cal.setTime(receivedDate);
        cal.add(Calendar.MINUTE, 10);
        return new SimpleDateFormat(pattern).format(cal.getTime());
    }
    
    private String decodeText(String text) throws UnsupportedEncodingException {
        if (text == null) {
            return null;
        }
        if (text.startsWith("=?GB") || text.startsWith("=?gb"))
            text = MimeUtility.decodeText(text);
        else
            text = new String(text.getBytes("ISO8859_1"));
        return text;
    }
}