xinyb
2024-08-30 f5cc47742dd3d2f2ffd8443ffc82a912683f7824
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
package com.yc.crm.mail.service;
 
import com.sun.mail.imap.IMAPStore;
import com.yc.action.grid.GridUtils;
import com.yc.crm.mail.entity.T482102Entity;
import com.yc.crm.mail.entity.t482101HEntity;
import com.yc.entity.AttachmentConfig;
import com.yc.entity.DataSourceEntity;
import com.yc.entity.attachment.AttachmentEntity;
import com.yc.entity.attachment.AttachmentWhereEntity;
import com.yc.factory.FactoryBean;
import com.yc.multiData.MultiDataSource;
import com.yc.sdk.shopping.service.imagedata.ShoppingImageDataIfc;
import com.yc.service.BaseService;
import com.yc.service.upload.AttachmentIfc;
import com.yc.utils.SessionKey;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
 
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.FlagTerm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
 
/**
 * @BelongsProject: eCoWorksV3
 * @BelongsPackage: com.yc.crm.mail.service
 * @author: xinyb
 * @CreateTime: 2024-08-06  09:57
 * @Description:
 */
@Service
public class MailImpl extends BaseService implements MailIfc {
 
    @Autowired
    MailAccountIfc emailAccountIfc;
    @Autowired
    ShoppingImageDataIfc imgData;
 
    final static String shoppingImageServer = AttachmentConfig.get("attachment.server");
 
    @Override
    public t482101HEntity saveReceivingMail(t482101HEntity m) {
        String sql = "set nocount on\n";
        try {
            if (StringUtils.isBlank(m.getDocCode())) {
                sql += "declare @docCode varchar(50) \n";
                sql += "exec sp_newdoccode 482101," + GridUtils.prossSqlParm(m.getUserCode()) + ",@docCode output \n";
                sql += "insert into t482101H(companyId,companyName,formId,docCode,docdate,PeriodID,postCode,postname,mailType,sender,receiver," +
                        "cc,bcc,subject,userCode,userName,content,file_unid,messageId,read_flag,delete_flag) values ";
                sql += "(" + GridUtils.prossSqlParm(m.getCompanyId()) + "," + GridUtils.prossSqlParm(m.getCompanyName()) + ",482101," +
                        "@docCode,convert(varchar(10),getdate(),120),convert(varchar(7),getdate(),120),"
                        + GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
                        +m.getMailType() + "," + GridUtils.prossSqlParm(m.getSender()) + "," +
                        GridUtils.prossSqlParm(m.getReceiver()) + "," + GridUtils.prossSqlParm(m.getCc()) + "," + GridUtils.prossSqlParm(m.getBcc()) + "," +
                        GridUtils.prossSqlParm(m.getSubject()) + "," + GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
                        GridUtils.prossSqlParm(m.getContent()) + "," + GridUtils.prossSqlParm(m.getFileUNID()) + "," + GridUtils.prossSqlParm(m.getMessageId()) + "," +
                        m.getReadFlag() + "," + m.getDeleteFlag() + ") \n";
                sql += "select @docCode as docCode";
                String docCode = jdbcTemplate.queryForObject(sql, String.class);
                if (StringUtils.isNotBlank(docCode)) {
                    m.setDocCode(docCode);
                }
            } else {
                updateReceivingMail(m);//修改
            }
            return m;
        } catch (Exception e) {
            throw e;
        }
    }
 
    @Override
    public void saveReceivingMailList(List<t482101HEntity> mail) {
        String sql = "set nocount on\n";
        try {
            sql += "declare @docCode varchar(50) \n";
            for (t482101HEntity m : mail) {//遍历内容
                sql += "exec sp_newdoccode 482101," + GridUtils.prossSqlParm(m.getUserCode()) + ",@docCode output \n";
                sql += "insert into t482101H(companyId,companyName,formId,docCode,docdate,PeriodID,postCode,postname,mailType,sender,receiver," +
                        "cc,bcc,subject,userCode,userName,content,file_unid,messageId,read_flag,delete_flag) values ";
                sql += "(" + GridUtils.prossSqlParm(m.getCompanyId()) + "," + GridUtils.prossSqlParm(m.getCompanyName()) + ",482101," +
                        "@docCode,convert(varchar(10),getdate(),120),convert(varchar(7),getdate(),120),"
                        + GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
                        +m.getMailType() + "," + GridUtils.prossSqlParm(m.getSender()) + "," +
                        GridUtils.prossSqlParm(m.getReceiver()) + "," + GridUtils.prossSqlParm(m.getCc()) + "," + GridUtils.prossSqlParm(m.getBcc()) + "," +
                        GridUtils.prossSqlParm(m.getSubject()) + "," + GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
                        GridUtils.prossSqlParm(m.getContent()) + "," + GridUtils.prossSqlParm(m.getFileUNID()) + "," + GridUtils.prossSqlParm(m.getMessageId()) + "," +
                        m.getReadFlag() + "," + m.getDeleteFlag() + ") \n";
//                sql +="exec postt482101V3 '' ,'',''";
            }
            jdbcTemplate.update(sql);
        } catch (Exception e) {
            throw e;
        }
    }
 
    @Override
    public Integer updateReceivingMail(t482101HEntity mail) {
        String sql = "set nocount on\n";
        try {
            sql += "update t482101H set sender=" + GridUtils.prossSqlParm(mail.getSender()) + ",receiver=" + GridUtils.prossSqlParm(mail.getReceiver()) + "," +
                    "cc=" + GridUtils.prossSqlParm(mail.getCc()) + ",bcc=" + GridUtils.prossSqlParm(mail.getBcc()) + ",subject=" + GridUtils.prossSqlParm(mail.getSubject()) + "," +
                    "content=" + GridUtils.prossSqlParm(mail.getContent()) + ",file_unid=" + GridUtils.prossSqlParm(mail.getFileUNID()) + ",mailType=" + mail.getMailType() + "," +
                    "updateTime=getdate() \n";
            sql += " where docCode=" + GridUtils.prossSqlParm(mail.getDocCode());
            sql += "select select @@ROWCOUNT";
            return jdbcTemplate.update(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
 
    @Override
    public Integer deleteReceivingMail(String userCode, String docCode) {
        String sql = "set nocount on\n";
        try {
            sql += "update t482101H deleteFlag=1 where userCode=" + GridUtils.prossSqlParm(userCode) + " and docCode=" + GridUtils.prossSqlParm(docCode) + "\n";//标记删除
            sql += "select select @@ROWCOUNT";
            return jdbcTemplate.update(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
 
    @Override
    public Integer deleteReceivingMail(String messageId) {
        String sql = "set nocount on\n";
        try {
            sql += "delete t482101H where messageId=" + GridUtils.prossSqlParm(messageId) + "\n";//删除
            sql += "select select @@ROWCOUNT";
            return jdbcTemplate.update(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
 
    @Override
    public t482101HEntity getReceivingMailInfo(String email, String docCode) {
        String sql = "set nocount on\n";
        try {
            sql += "select top 1 DocCode,sender,receiver,subject,content,file_unid as fileUNID from t482101H where receiver = '" + email + "' and docCode=" + GridUtils.prossSqlParm(docCode);
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HEntity.class)).get(0);
        } catch (Exception e) {
            throw e;
        }
    }
 
    @Override
    public List<t482101HEntity> getReceivingMailList(String email, Integer mailType, boolean isNoRead) {
        String sql = "set nocount on\n";
        try {
            sql += "select DocCode,sender,receiver,subject,content,file_unid as fileUNID " +
                    "from t482101H ";
            if (isNoRead) {//未读执行
                sql += "where receiver ='" + email + "' and  isnull(readFlag,0)= 0";
            } else {//已读
                sql += "where receiver ='" + email + "' and  mailType=" + mailType;
            }
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HEntity.class));
        } catch (Exception e) {
            throw e;
        }
    }
 
 
    @Override
    public List<t482101HEntity> getMailReceiving(T482102Entity emailEntity, HttpServletRequest request) throws MessagingException {
        String imapServer = emailEntity.getReceiveHost();//"imap.qq.com";
        String user = emailEntity.getEmail();//"xxx@qq.com";
        String pwd = emailEntity.getPassword();//"xxxx";
 
        HashMap IAM = new HashMap();
        //带上IMAP ID信息,由key和value组成,例如name,version,vendor,support-email等。
        IAM.put("name", emailEntity.getAliasEmail());
        IAM.put("version", emailEntity.getDocVersion() + "");
        IAM.put("vendor", emailEntity.getCompanyName());
        IAM.put("support-email", emailEntity.getEmail());
        //创建会话
        Session session = Session.getInstance(new Properties(), new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pwd);
            }
        });
        //存储对象
        IMAPStore store = (IMAPStore) session.getStore(emailEntity.getReceiveProtocol());//imap协议或pop3协议类型(推荐你使用IMAP协议来存取服务器上的邮件。)
        //连接
        store.connect(imapServer, user, pwd);
        store.id(IAM);//163邮箱需要,不然会报:A3 NO SELECT Unsafe Login. Please contact kefu@188.com for help
        Folder folder = null;
        try {
            // 获得收件箱
            folder = store.getFolder("INBOX");
            // 以读写模式打开收件箱
            folder.open(Folder.READ_WRITE);
            //false 表示未读
            FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), true);
            //获得收件箱的邮件列表
            Message[] messages = folder.search(flagTerm);
            //返回邮箱封装内容
            return setMailContent(messages, user, request);
        } catch (NoSuchProviderException e) {
            throw e;
        } catch (MessagingException e) {
            throw e;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (folder != null) {
                    folder.close(false);
                }
                if (store != null) {
                    store.close();
                }
            } catch (MessagingException e) {
                throw e;
            }
        }
    }
 
    @Override
    public void sendingMail(t482101HEntity t482101H, HttpServletRequest request) throws Exception {
        try {
            //根据当前用户查询绑定的邮箱信息
            T482102Entity emailEntity = emailAccountIfc.getAccountInfo(t482101H.getUserCode(), t482101H.getSender());//返回邮箱的账号信息
            if (emailEntity == null || StringUtils.isBlank(emailEntity.getEmail())) {
                if (StringUtils.isBlank(t482101H.getDocCode())) {
                    t482101H.setMailType(0);//草稿箱状态
                    t482101H = saveReceivingMail(t482101H);//保存到草稿箱内
                }
                throw new Exception("找不到邮箱:" + t482101H.getSender() + "配置信息请完善。邮件已保存到草稿箱#" + t482101H.getDocCode());
            }
            //有发送的邮件保存到后台数据库
            //邮箱服务器配置
            Properties properties = new Properties();
            properties.setProperty("mail.smtp.host", emailEntity.getSmtpHost());
            properties.setProperty("mail.smtp.port", emailEntity.getSmtpPort() + "");
            properties.setProperty("mail.smtp.auth", "true");
            properties.setProperty("mail.smtp.starttls.enable", "true");
            //
            String sendEmail = emailEntity.getEmail();//发件人
            String sendPassword = emailEntity.getPassword();//密码
            String recipientEmail = t482101H.getReceiver();//收件人
            Session session = Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(sendEmail, sendPassword);
                }
            });
 
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(sendEmail));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
            message.setSubject(t482101H.getSubject());
 
            String Unique_ID = UUID.randomUUID().toString();//unId码
            String message_id = "<onBus_" + Unique_ID + "_" + t482101H.getDocCode() + ">";//系统单号唯一码
            message.setHeader("Message-ID", message_id);//系统内部唯一码
            t482101H.setMessageId(message_id);//messageId赋值
 
            if (StringUtils.isNotBlank(t482101H.getCc())) {//抄送
                String[] cc = t482101H.getCc().split(";");
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(StringUtils.join(cc, ",")));
            }
            if (StringUtils.isNotBlank(t482101H.getBcc())) {//密送
                String[] bcc = t482101H.getBcc().split(";");
                message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(StringUtils.join(bcc, ",")));
            }
 
            //创建多部分消息
            Multipart multipart = new MimeMultipart();
 
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(t482101H.getContent());//内容
            multipart.addBodyPart(textPart);
 
            //下面附件内容
            if (StringUtils.isNotBlank(t482101H.getFileUNID())) {//有附件内容
                //获取到附件内容
                List<AttachmentEntity> attachmentEntities = getAttachmentEntityList(t482101H.getFileUNID());
                if (attachmentEntities != null && attachmentEntities.size() > 0) {
                    for (AttachmentEntity a : attachmentEntities) {
                        InputStream inputStream = new ByteArrayInputStream(a.getOriginalPicture());
                        File file = new File(a.getOriginalFileName());
                        FileUtils.copyInputStreamToFile(inputStream, file);
                        MimeBodyPart bodyPart = new MimeBodyPart();
                        bodyPart.attachFile(file);
                        bodyPart.setFileName(a.getOriginalFileName());
                        multipart.addBodyPart(bodyPart);
                    }
                }
            }
            message.setContent(multipart);
            try {
                if(StringUtils.isBlank(t482101H.getDocCode())){//不在草稿箱有单号
                    saveReceivingMail(t482101H);//保存后发送
                }else{
                    t482101H.setMailType(2);//发件箱状态
                    updateMailDrafts(t482101H);//更新成草稿箱
                }
                Transport.send(message);//发送
            } catch (MessagingException m) {//发送异常处理
                t482101H.setMailType(0);//草稿箱状态
                updateMailDrafts(t482101H);//更新成草稿箱
                throw new Exception("发送邮件异常,邮件已保存在草稿箱。异常原因:" + m.getCause() != null ? m.getCause().getMessage() : m.getMessage());
            }
        } catch (Exception e) {
            throw e;
        }
    }
 
    @Override
    public Integer updateMailDrafts(t482101HEntity mail) {
        String sql = "set nocount on\n";
        try {
            sql += "update t482101H set sender=" + GridUtils.prossSqlParm(mail.getSender()) + ",receiver=" + GridUtils.prossSqlParm(mail.getReceiver()) + "," +
                    "cc=" + GridUtils.prossSqlParm(mail.getCc()) + ",bcc=" + GridUtils.prossSqlParm(mail.getBcc()) + ",subject=" + GridUtils.prossSqlParm(mail.getSubject()) + "," +
                    "content=" + GridUtils.prossSqlParm(mail.getContent()) + ",file_unid=" + GridUtils.prossSqlParm(mail.getFileUNID()) + ",mailType=" + mail.getMailType() + "," +
                    "updateTime=getdate() \n";
            sql += " where docCode=" + GridUtils.prossSqlParm(mail.getDocCode());
            sql += "select select @@ROWCOUNT";
            return jdbcTemplate.update(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
 
    @Override
    public Integer deleteMailDrafts(String docCode) {
        String sql = "set nocount on\n";
        try {
            sql += "delete t482101H where docCode=" + GridUtils.prossSqlParm(docCode);
            sql += "select select @@ROWCOUNT";
            return jdbcTemplate.update(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
 
    /**
     * 收件箱返回的信息进行封装处理
     *
     * @param messages
     * @return
     * @throws MessagingException
     * @throws IOException
     */
    public List<t482101HEntity> setMailContent(Message[] messages, String receiver, HttpServletRequest request) throws Exception {
        try {
            List<t482101HEntity> t482101HEntityList = new ArrayList<>();
            HttpSession session = request.getSession();
            List<String> messageIdList = getMessageIdList(receiver);
            Message m = null;
            for (int i = 0; i < messages.length; i++) {
                m = messages[i];
                String messageId = m.getHeader("Message-ID")[0];
                if (messageIdList != null && messageIdList.contains(messageId)) {
                    if (m.isSet(Flags.Flag.DELETED)) {//邮件是否需要删除
                        //删除系统里的邮件
                        deleteReceivingMail(messageId);
                    }
                    //已经存在就不需要再次封装处理
                    continue;
                }
 
                t482101HEntity mail = new t482101HEntity();
                mail.setMessageId(messageId);//获取邮件唯一ID
                mail.setMailType(1);//收件
                if (m.isSet(Flags.Flag.SEEN)) {//邮件已标记为已读
                    mail.setReadFlag(1);//已读
                }
                if (m.isExpunged()) {//检查一个消息是否已被删除。‌
                    mail.setDeleteFlag(1);//已删除
                }
                if (m.isSet(Flags.Flag.ANSWERED)) {//邮件是否已回复
 
                }
                if (m.isSet(Flags.Flag.DRAFT)) {//是否是草稿箱
                    mail.setMailType(0);//是草稿箱
                }
 
                mail.setClassType(1);
                mail.setUserCode((String) session.getAttribute(SessionKey.USERCODE));
                mail.setUserName((String) session.getAttribute(SessionKey.USERNAME));
                mail.setCompanyId((String) session.getAttribute(SessionKey.COMPANY_ID));
                mail.setCompanyName((String) session.getAttribute(SessionKey.COMPANY_NAME));
                mail.setSubject(m.getSubject());//标题
                String result = "";
                if (m.isMimeType("text/plain")) {
                    result = m.getContent().toString();
                } else if (m.isMimeType("text/html")) {//html格式
                    result = m.getContent().toString();
                } else if (m.isMimeType("multipart/*")) {
                    List<String> fileSeq = new ArrayList<>();
                    MimeMultipart mimeMultipart = (MimeMultipart) m.getContent();
                    String uuId = UUID.randomUUID().toString().toUpperCase();//生成uuid
                    result = getTextFromMimeMultipart(mimeMultipart, uuId, fileSeq, request);
                    if (fileSeq.size() > 0) {//有附件内容保存
                        mail.setFileUNID(uuId + ";" + StringUtils.join(fileSeq, ";"));
                    }
                } else {
                    result = m.getContent().toString();
                }
                mail.setContent(result);//保存内容
                String from = MimeUtility.decodeText(m.getFrom()[0].toString());
                InternetAddress internetAddress = new InternetAddress(from);
                mail.setSender(internetAddress.getAddress());//发件人
                from = MimeUtility.decodeText(m.getRecipients(Message.RecipientType.TO)[0].toString());
                internetAddress = new InternetAddress(from);
                mail.setReceiver(internetAddress.getAddress());//收件人
                mail.setReceiver(receiver);//统一成一个收件人
                String cc = "";//抄送人
                Address[] ccAddress = m.getRecipients(Message.RecipientType.CC);
                if (ccAddress != null && ccAddress.length > 0) {
                    for (Address c : ccAddress) {
                        from = MimeUtility.decodeText(c.toString());
                        internetAddress = new InternetAddress(from);
                        cc += internetAddress.getAddress() + ";";
                    }
                    cc = cc.substring(0, cc.lastIndexOf(";"));
                }
                mail.setCc(cc);
                String bcc = "";//密送
                Address[] bccAddress = m.getRecipients(Message.RecipientType.BCC);
                if (bccAddress != null && bccAddress.length > 0) {
                    for (Address c : bccAddress) {
                        from = MimeUtility.decodeText(c.toString());
                        internetAddress = new InternetAddress(from);
                        bcc += internetAddress.getAddress() + ";";
                    }
                    bcc = bcc.substring(0, bcc.lastIndexOf(";"));
                }
                mail.setBcc(bcc);//密送人
                t482101HEntityList.add(mail);
            }
            return t482101HEntityList;
        } catch (Exception e) {
            throw e;
        }
    }
 
    // 辅助方法,用于递归获取纯文本邮件内容
    private String getTextFromMimeMultipart(MimeMultipart mimeMultipart, String uuId, List<String> fileSeq, HttpServletRequest request) throws Exception {
        int count = mimeMultipart.getCount();
        if (count == 0) {
            throw new MessagingException("Multipart with no body parts");
        }
        boolean multipartAlternative = isMultipartAlternative(mimeMultipart);
        StringBuilder result = new StringBuilder();
        if (multipartAlternative) {
            for (int i = 0; i < count; i++) {
                BodyPart bodyPart = mimeMultipart.getBodyPart(i);
                if (bodyPart.isMimeType("text/plain")) {
                    result.append(bodyPart.getContent());
                    break; // 只获取第一个纯文本内容
                }
            }
        } else {
            for (int i = 0; i < count; i++) {
                BodyPart bodyPart = mimeMultipart.getBodyPart(i);
                if (bodyPart.isMimeType("text/plain")) {
                    result.append(bodyPart.getContent());
                } else if (bodyPart.isMimeType("image/*")) {//图片
                    result.append(saveFileAndImage(bodyPart, "image", uuId, request));
                } else if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {//附件
                    fileSeq.add(saveFileAndImage(bodyPart, Part.ATTACHMENT, uuId, request));
                } else if (bodyPart.isMimeType("multipart/*")) {
                    result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent(), uuId, fileSeq, request));
                }
            }
        }
        return result.toString();
    }
 
    // 辅助方法,判断是否为multipart/alternative类型的邮件
    private boolean isMultipartAlternative(MimeMultipart mimeMultipart) throws Exception {
        boolean textPlainFound = false;
        boolean textHtmlFound = false;
        int count = mimeMultipart.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart bodyPart = mimeMultipart.getBodyPart(i);
            if (bodyPart.isMimeType("text/plain")) {
                textPlainFound = true;
            } else if (bodyPart.isMimeType("text/html")) {
                textHtmlFound = true;
            }
        }
        return textPlainFound && textHtmlFound;
    }
 
    private String saveFileAndImage(BodyPart bodyPart, String type, String unId, HttpServletRequest request) throws Exception {
        try {
            String fileName = MimeUtility.decodeText(bodyPart.getFileName());
            if (type.equals("image")) {
                String pattern = ".*\\.(jpg|jpeg|png|gif)$";
                fileName = Pattern.matches(pattern, fileName) ? fileName : fileName + ".jpg";
            }
            File file = new File(fileName);
            FileUtils.copyInputStreamToFile(bodyPart.getInputStream(), file);
            AttachmentEntity attachmentEntity = new AttachmentEntity();
            attachmentEntity.setDoccode("");
            attachmentEntity.setRowId("");
            attachmentEntity.setFormId(482101);
            attachmentEntity.setUnid(unId);
            attachmentEntity.setSeq(null);
            attachmentEntity.setFieldId("file");
            attachmentEntity.setPhysicalFile(file.getName());
            attachmentEntity.setOriginalFileName(file.getName());
            AttachmentIfc attachmentIfc = (AttachmentIfc) FactoryBean.getBean("AttachmentImpl");
            //保存附件
            AttachmentWhereEntity attachmentWhereEntity = attachmentIfc.saveAttachment(attachmentEntity, file, "2");
            if (type.equals("image")) {
                //输出 url
//                return imgData.getImageUrl(attachmentWhereEntity.getUnid() + ";" + attachmentWhereEntity.getSeq(), null,
//                        null, true, true, null);
                DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(request);
                return shoppingImageServer + "/uploads/attachment/" + dataSourceEntity.getDbId() + "/482101/" + attachmentWhereEntity.getUnid() + "@p@" + attachmentWhereEntity.getSeq() + ".jpg";
            } else if (type.equals(Part.ATTACHMENT)) {
                return attachmentWhereEntity.getSeq() + "";
            } else {
                return null;
            }
        } catch (Exception e) {
            throw e;
        }
    }
 
    @Override
    public List<AttachmentEntity> getAttachmentEntityList(String unIdSeq) {
        String unId = null;
        if (StringUtils.isBlank(unIdSeq)) {
            return null;
        }
        String[] array = unIdSeq.split(";");
        unId = array[0];//在有值时候第一个必定是unId
        ArrayList<String> seqs = new ArrayList<>(Arrays.asList(array));
        seqs.remove(0);//去掉第一个元素(UNID)
        String sql = " set nocount on \n"
                + " declare @unid varchar(50) = " + GridUtils.prossSqlParm(unId) + "  \n";
        sql += " select UNID,seq,DocCode,RowId,FieldId,FormId, \n"
                + " PhysicalPath,PhysicalFile,OriginalFileName,FileSize,FileType, \n"
                + " AuthorCode,AuthorName,SmallPicPath,UploadTime,OriginalPicture \n"
                + " from _sys_Attachment \n"
                + " where unid = @unid ";
        if (seqs.size() > 0) {
            sql += " and seq in(" + StringUtils.join(seqs, ",") + ")\n";
        }
        List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql);
        List<AttachmentEntity> attachmentList = new ArrayList<AttachmentEntity>();
        for (int i = 0; list != null && i < list.size(); i++) {
            AttachmentEntity attachment = new AttachmentEntity();
            attachment.setOriginalFileName(list.get(i).get("OriginalFileName") == null ? null : (String) list.get(i).get("OriginalFileName"));
            //附件处理
            attachment.setOriginalPicture(list.get(i).get("OriginalPicture") == null ? null : (byte[]) list.get(i).get("OriginalPicture"));
            attachmentList.add(attachment);
        }
        return attachmentList;
    }
 
    @Override
    public List<String> getMessageIdList(String receiver) {
        List<String> messageId = null;
        String sql = " set nocount on \n";
        try {
            sql += "select messageId from t482101H where receiver='" + receiver + "'";
            List<t482101HEntity> message = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HEntity.class));
            if (message != null && message.size() > 0) {
                messageId = new ArrayList<>();
                messageId = message.stream().map(t482101HEntity::getMessageId).distinct().collect(Collectors.toList());//去重
            }
            return messageId;
        } catch (Exception e) {
            throw e;
        }
    }
}