xinyb
3 天以前 3b74e3df72726e188d36393ecfd7964d095ef7e8
提交 | 用户 | age
7caeae 1 package com.yc.crm.mail.service;
X 2
3 import com.sun.mail.imap.IMAPBodyPart;
4 import com.sun.mail.imap.IMAPStore;
18553a 5 import com.yc.action.grid.GridUtils;
F 6 import com.yc.crm.mail.action.MailPush;
7caeae 7 import com.yc.crm.mail.entity.FoundationEntity;
X 8 import com.yc.crm.mail.entity.MailFileEntity;
9 import com.yc.crm.mail.entity.T482102Entity;
10 import com.yc.crm.mail.entity.t482101HEntity;
11 import com.yc.entity.attachment.AttachmentEntity;
18553a 12 import com.yc.factory.FactoryBean;
7caeae 13 import com.yc.service.BaseService;
X 14 import org.apache.commons.io.FileUtils;
15 import org.apache.commons.lang3.StringUtils;
16 import org.springframework.beans.factory.annotation.Autowired;
17 import org.springframework.stereotype.Service;
18
19 import javax.mail.*;
20 import javax.mail.internet.*;
3b74e3 21 import javax.mail.search.ComparisonTerm;
X 22 import javax.mail.search.ReceivedDateTerm;
7caeae 23 import javax.servlet.http.HttpServletRequest;
X 24 import java.io.*;
25 import java.text.SimpleDateFormat;
26 import java.util.*;
27
28 import static com.yc.crm.mail.service.MailImpl.shoppingImageServer;
29
30 /**
31  * @BelongsProject: eCoWorksV3
32  * @BelongsPackage: com.yc.crm.mail.service
33  * @author: xinyb
34  * @CreateTime: 2024-09-12  10:30
35  * @Description:
36  */
37 @Service
38 public class MailServiceImpl extends BaseService implements MailServiceIfc {
39     @Autowired
40     MailIfc mailIfc;
41     @Autowired
42     MailAccountIfc mailAccountIfc;
195685 43     @Autowired
X 44     MailFileIfc mailFileIfc;
7caeae 45
X 46     @Override
47     public void receivingEmails(T482102Entity emailEntity, FoundationEntity foundation) throws MessagingException {
048b74 48         String protocol = emailEntity.getReceiveProtocol().toLowerCase();//接收协议 imap pop3
X 49         String server = emailEntity.getReceiveHost();//"imap.qq.com";
50         Integer port = emailEntity.getReceivePort();//993
51         String user = emailEntity.getReceiveEmail();//邮箱
52         String pwd = emailEntity.getReceivePassword();//密码
7caeae 53
X 54         Properties properties = new Properties();
57c8bf 55         properties.setProperty("mail.store.protocol", protocol); // IMAP over SSL
048b74 56         if (protocol.contains("imap")) {//接收协议imap
57c8bf 57             properties.setProperty("mail.imaps.host", server);
X 58             properties.setProperty("mail.imaps.port", port + "");
048b74 59         } else if (protocol.contains("pop3")) {//接收协议pop3
57c8bf 60             properties.setProperty("mail.pop3.host", server);
X 61             properties.setProperty("mail.pop3.port", port + "");
048b74 62         } else {//其他(再加)
57c8bf 63             properties.setProperty("mail.imaps.host", server);
X 64             properties.setProperty("mail.imaps.port", port + "");
048b74 65         }
X 66 //        properties.put("mail.imaps.starttls.enable", "true");//// IMAP 协议设置 STARTTLS
7caeae 67
X 68         HashMap IAM = new HashMap();
69         //带上IMAP ID信息,由key和value组成,例如name,version,vendor,support-email等。
048b74 70         IAM.put("name", user);
7caeae 71         IAM.put("version", emailEntity.getDocVersion() + "");
X 72         IAM.put("vendor", emailEntity.getCompanyName());
73         IAM.put("support-email", emailEntity.getEmail());
74         //创建会话
75         Session session = Session.getInstance(properties, new Authenticator() {
76             @Override
77             protected PasswordAuthentication getPasswordAuthentication() {
78                 return new PasswordAuthentication(user, pwd);
79             }
80         });
81         //存储对象
048b74 82         IMAPStore store = (IMAPStore) session.getStore(protocol);//imap协议或pop3协议类型(推荐你使用IMAP协议来存取服务器上的邮件。)
7caeae 83         //连接
048b74 84         store.connect(server, user, pwd);
7caeae 85         store.id(IAM);//163邮箱需要,不然会报:A3 NO SELECT Unsafe Login. Please contact kefu@188.com for help
X 86         Folder folder = null;
87         try {
88             // 获得收件箱
89             folder = store.getFolder("INBOX");
90             // 以读写模式打开收件箱
91             folder.open(Folder.READ_WRITE);
7cf738 92
X 93             //false 表示未读 ,true已读,获得收件箱的邮件列表
7caeae 94 //            FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), true);
X 95 //            Message[] messages = folder.search(flagTerm);
7cf738 96
3b74e3 97             //获取收件箱邮件(30天)
X 98             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
99             String time=emailEntity.getCreateTime();
100             Date dateTime=sdf.parse(time);
101             Date thirtyDaysAgo = new Date(dateTime.getTime() - (30 * 24 * 60 * 60 * 1000L)); // 30天前的日期
102             Message[] messages = folder.search(new ReceivedDateTerm(ComparisonTerm.GE, thirtyDaysAgo));
103
104 //            SearchTerm start=new FromTerm(new date)
105 //            SearchTerm end=new BeforeTerm(new Date(""));//开始
106 //            Message[] messages = folder.search(new AndTerm(start,end));//folder.getMessages();
7cf738 107
7caeae 108             //邮箱封装保存
3b74e3 109             setMailContent(messages, emailEntity, foundation,false);
7caeae 110         } catch (NoSuchProviderException e) {
X 111             throw e;
112         } catch (MessagingException e) {
113             throw e;
ad7c8d 114         } catch (IOException e) {
X 115             throw new RuntimeException(e);
7caeae 116         } catch (Exception e) {
X 117             throw new RuntimeException(e);
118         } finally {
119             try {
120                 if (folder != null) {
121                     folder.close(false);
122                 }
123                 if (store != null) {
124                     store.close();
125                 }
126             } catch (MessagingException e) {
127                 throw e;
128             }
129         }
130     }
131
132
133     @Override
134     public void sendEmails(t482101HEntity t482101H, HttpServletRequest request) throws Exception {
135         try {
136             //根据当前用户查询绑定的邮箱信息
137             T482102Entity emailEntity = mailAccountIfc.getAccountInfo(t482101H.getUserCode(), t482101H.getSender());//返回邮箱的账号信息
138             if (emailEntity == null || StringUtils.isBlank(emailEntity.getSmtpEmail())) {
139                 if (StringUtils.isBlank(t482101H.getDocCode())) {
140                     t482101H.setMailType(0);//草稿箱状态
141                     t482101H = mailIfc.saveReceivingMail(t482101H);//保存到草稿箱内
142                 }
f6ae0b 143                 throw new MessagingException("找不到邮箱:" + t482101H.getSender() + "配置信息请完善。邮件已保存到草稿箱#" + t482101H.getDocCode());
7caeae 144             }
X 145             //有发送的邮件保存到后台数据库
146             //邮箱服务器配置
147             Properties properties = new Properties();
048b74 148             properties.setProperty("mail.smtp.auth", "true");// // 设置SMTP是否需要认证 指定客户端是否向邮件服务器提交认证
X 149             properties.setProperty("mail.transport.protocol", "smtp");//设置传输协议 指定采用的邮件发送协议。
57c8bf 150             properties.setProperty("mail.smtp.ssl.enable", emailEntity.isSmtpSSL() + "");// // 设置启用SSL加密
7caeae 151             properties.setProperty("mail.smtp.host", emailEntity.getSmtpHost());
X 152             properties.setProperty("mail.smtp.port", emailEntity.getSmtpPort() + "");
18553a 153             //Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1 by danaus 2024-09-23 11:01
b7ef4b 154             // properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
X 155             // MailSSLSocketFactory sf = new MailSSLSocketFactory("TLSv1.2");
156             // properties.put("mail.smtp.ssl.socketFactory", sf);
157             // properties.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
048b74 158 //            properties.setProperty("mail.smtp.starttls.enable", "true");//// SMTP 协议设置 STARTTLS  开启tls
X 159 //            properties.setProperty("mail.smtp.socketFactory.port", emailEntity.getSmtpPort() + "");
7caeae 160
X 161             //
162             String sendEmail = emailEntity.getSmtpEmail();//发件人
163             String sendPassword = emailEntity.getSmtpPassword();//密码
164             String recipientEmail = StringUtils.join(t482101H.getReceiver(), ",");//收件人
165             Session session = Session.getInstance(properties, new Authenticator() {
166                 @Override
167                 protected PasswordAuthentication getPasswordAuthentication() {
168                     return new PasswordAuthentication(sendEmail, sendPassword);
169                 }
170             });
171
172             MimeMessage message = new MimeMessage(session);
173             message.setFrom(new InternetAddress(sendEmail));
174             message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
57c8bf 175             message.setSubject(t482101H.getSubject());//主题
7caeae 176
X 177             String Unique_ID = "<onBus_" + UUID.randomUUID().toString().toUpperCase() + "@mail.com>";//系统单号唯一码
178             message.setHeader("Message-ID", Unique_ID);//系统内部唯一码
179             t482101H.setMessageId(Unique_ID);//messageId赋值
180
181             if (t482101H.getCc() != null && t482101H.getCc().size() > 0) {//抄送
182                 message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(StringUtils.join(t482101H.getCc(), ",")));
183             }
184             if (t482101H.getBcc() != null && t482101H.getBcc().size() > 0) {//密送
185                 message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(StringUtils.join(t482101H.getBcc(), ",")));
186             }
187
188             //创建多部分消息
189             Multipart multipart = new MimeMultipart();
190
191             MimeBodyPart textPart = new MimeBodyPart();
192             textPart.setText(t482101H.getContent());//内容
193             multipart.addBodyPart(textPart);
194
195             //下面附件内容
196             if (StringUtils.isNotBlank(t482101H.getAttachmentList())) {//有附件内容
197                 //获取到附件内容
195685 198                 List<AttachmentEntity> attachmentEntities = mailFileIfc.getAttachmentEntityList(t482101H.getAttachmentList());
7caeae 199                 if (attachmentEntities != null && attachmentEntities.size() > 0) {
X 200                     for (AttachmentEntity a : attachmentEntities) {
201                         InputStream inputStream = new ByteArrayInputStream(a.getOriginalPicture());
202                         File file = new File(a.getOriginalFileName());
203                         FileUtils.copyInputStreamToFile(inputStream, file);
204                         MimeBodyPart bodyPart = new MimeBodyPart();
205                         bodyPart.attachFile(file);
206                         bodyPart.setFileName(a.getOriginalFileName());
207                         multipart.addBodyPart(bodyPart);
208                     }
209                 }
210             }
211             message.setContent(multipart);
212             try {
213                 if (StringUtils.isBlank(t482101H.getDocCode())) {//不在草稿箱有单号
214                     mailIfc.saveReceivingMail(t482101H);//保存后发送
215                 } else {
216                     t482101H.setMailType(2);//发件箱状态
217                     mailIfc.updateMailDrafts(t482101H);//更新成发件箱
218                 }
219                 Transport.send(message);//发送
220             } catch (MessagingException m) {//发送异常处理
221                 t482101H.setMailType(0);//草稿箱状态
222                 mailIfc.updateMailDrafts(t482101H);//更新成草稿箱
048b74 223                 throw new MessagingException("发送邮件异常,邮件已保存在草稿箱。异常原因:" + m.getMessage() + "#" + t482101H.getDocCode());
7caeae 224             }
X 225         } catch (Exception e) {
226             throw e;
227         }
228     }
229
57c8bf 230     @Override
X 231     public Integer setQuickReply(String docCode, String content) throws MessagingException {
232         String sql = "set nocount on\n";
233         try {
234             sql += "declare @docCode varchar(200) ='" + docCode + "'\n";
235             sql += "update t482101H set receive_time=getdate() where docCode=@docCode\n";//更新回复时间
236             sql += "select a.subject,a.sender,a.receiver,a.messageid,b.smtpEmail,b.smtpPassword,b.smtpHost,b.smtpPort,isnull(b.smtpSSL,0) as smtpSSL " +
237                     " from t482101H a join t482102 b on a.receiver=b.smtpEmail where docCode=@docCode";
238             Map<String, Object> map = jdbcTemplate.queryForMap(sql);
239             if (map == null || map.get("sender") == null) {
240                 throw new MessagingException("回复人信息查找不到,请检查docCode唯一码");
241             }
242             String receiver = (String) map.get("sender");//收件人
243             String sender = (String) map.get("receiver");//发件人
244             String smtpSSL = map.get("smtpSSL").equals(0) ? "false" : "true";
245
246             Properties props = new Properties();
247             props.setProperty("mail.smtp.auth", "true");
248             props.setProperty("mail.transport.protocol", "smtp");//设置传输协议 指定采用的邮件发送协议。
249             props.setProperty("mail.smtp.ssl.enable", smtpSSL);// // 设置启用SSL加密
250             props.setProperty("mail.smtp.host", (String) map.get("smtpHost"));
251             props.setProperty("mail.smtp.port", map.get("smtpPort") + "");
252 //            props.setProperty("mail.smtp.starttls.enable", "true");
253
254             Session session = Session.getInstance(props, new javax.mail.Authenticator() {
255                 protected PasswordAuthentication getPasswordAuthentication() {
256                     return new PasswordAuthentication((String) map.get("smtpEmail"), (String) map.get("smtpPassword"));
257                 }
258             });
259
260             Message replyMessage = new MimeMessage(session);
261             replyMessage.setFrom(new InternetAddress(sender));
262             replyMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));//收件人
263             replyMessage.setSubject("Re: " + map.get("subject"));//主题
264
265             // 引用原邮件
266             replyMessage.setHeader("In-Reply-To", (String) map.get("messageid"));
267             replyMessage.setHeader("References", (String) map.get("messageid"));
268
269             replyMessage.setText(content);//这里是回复的内容
270
271             Transport.send(replyMessage);
272
273             return 1;
274         } catch (MessagingException e) {
275             throw new MessagingException("快速回复异常:" + e.getMessage());
276         } catch (Exception e) {
277             throw e;
278         }
279     }
280
7caeae 281     /**
X 282      * 收件箱返回的信息进行封装处理
283      *
284      * @param messages
285      * @return
286      * @throws MessagingException
287      * @throws IOException
288      */
18553a 289     @Override
3b74e3 290     public void setMailContent(Message[] messages, T482102Entity email, FoundationEntity foundation,boolean hasPush) throws
57c8bf 291             Exception {
7caeae 292         try {
X 293             List<t482101HEntity> t482101HEntityList = new ArrayList<>();
7cf738 294             List<String> messageIdList = mailIfc.getMessageIdList(email.getReceiveEmail());//存在系统表里的邮件
7caeae 295             Message m = null;
53241c 296             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7caeae 297             for (int i = 0; i < messages.length; i++) {
X 298                 m = messages[i];
3b74e3 299                 String messageId = m.getHeader("Message-ID")[0];
X 300                 if (messageIdList != null && messageIdList.contains(messageId)) {//存在就不组装
0c7568 301                     continue;
X 302                 }
3b74e3 303                 Date deliveryTime = m.getReceivedDate();//收件时间
X 304                 Date senderTime = m.getSentDate();//发件时间
53241c 305                 if (senderTime == null) {
X 306                     senderTime = senderTime;
307                 }
308
3b74e3 309                 t482101HEntity mail = new t482101HEntity();
X 310                 mail.setSenderTime(sdf.format(senderTime));//发件时间
311                 mail.setReceivingTime(sdf.format(deliveryTime));//收件时间
312                 mail.setMessageId(messageId);//获取邮件唯一ID
313                 mail.setMailType(1);//收件
314                 if (m.isSet(Flags.Flag.SEEN)) {//邮件已标记为已读
315                     mail.setReadFlag(1);//已读
7caeae 316                 }
3b74e3 317                 if (m.isExpunged()) {//检查一个消息是否已被删除。‌
X 318                     mail.setDeleteFlag(1);//已删除
319                 }
320                 if (m.isSet(Flags.Flag.ANSWERED)) {//邮件是否已回复
321
322                 }
323                 if (m.isSet(Flags.Flag.DRAFT)) {//是否是草稿箱
324                     mail.setMailType(0);//是草稿箱
325                 }
326                 mail.setUserCode(foundation.getUserCode());
327                 mail.setUserName(foundation.getUserName());
328                 mail.setCompanyId(foundation.getCompanyId());
329                 mail.setCompanyName(foundation.getCompanyName());
330                 mail.setClassType(1);
331                 mail.setSubject(m.getSubject());//标题
332                 Date date = m.getReceivedDate();//时间
333                 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
334                 mail.setReceiveTime(formatter.format(date));
335                 String result = "";
336                 StringBuilder plainText = new StringBuilder();//纯文本
337                 if (m.isMimeType("text/plain")) {
338                     plainText.append(m.getContent());
339                 } else if (m.isMimeType("text/html")) {//html格式
340                     result = m.getContent().toString();
341                 } else if (m.isMimeType("multipart/*")) {
342                     MailFileEntity mailFile = new MailFileEntity();//附件
343                     List<MailFileEntity.MailBodyPart> part = new ArrayList<>();
344                     String unId = UUID.randomUUID().toString().toUpperCase();
345                     StringBuilder attachment = new StringBuilder();
346                     result = getTextFromMimeMultipart((MimeMultipart) m.getContent(), plainText, part, unId, attachment, foundation.getDbId());
347                     mailFile.setPart(part);
348                     mailFile.setUnId(unId);//生成uuid
349                     mail.setMailFile(mailFile);//附件添加到里面
350                     if (StringUtils.isNotBlank(attachment)) {//附件游标保存
351                         mail.setAttachFlag(1);
352                         mail.setAttachmentList(unId + attachment.toString());
353                     }
354                 } else {
355                     result = m.getContent().toString();
356                 }
357                 mail.setContent(result);//保存内容
358                 mail.setPlainText(plainText.toString().trim());//明文
359                 String from = MimeUtility.decodeText(m.getFrom()[0].toString());
360                 InternetAddress internetAddress = new InternetAddress(from);
361                 mail.setSenderName(internetAddress.getPersonal());//发件人名称
362                 mail.setSender(internetAddress.getAddress());//发件人
363                 from = MimeUtility.decodeText(m.getRecipients(Message.RecipientType.TO)[0].toString());
364                 internetAddress = new InternetAddress(from);
365 //                mail.setReceiver(internetAddress.getAddress());//收件人
366                 List<String> receivers = new ArrayList<>();//抄送人
367                 receivers.add(email.getReceiveEmail());
368                 mail.setReceiver(receivers);//统一成一个收件人
369
370                 Address[] ccAddress = m.getRecipients(Message.RecipientType.CC);
371                 if (ccAddress != null && ccAddress.length > 0) {
372                     List<String> cc = new ArrayList<>();//抄送人
373                     for (Address c : ccAddress) {
374                         from = MimeUtility.decodeText(c.toString());
375                         internetAddress = new InternetAddress(from);
376                         cc.add(internetAddress.getAddress());
377                     }
378                     mail.setCc(cc);
379                 }
380                 Address[] bccAddress = m.getRecipients(Message.RecipientType.BCC);
381                 if (bccAddress != null && bccAddress.length > 0) {
382                     List<String> bcc = new ArrayList<>();//密送
383                     for (Address c : bccAddress) {
384                         from = MimeUtility.decodeText(c.toString());
385                         internetAddress = new InternetAddress(from);
386                         bcc.add(internetAddress.getAddress());
387                     }
388                     mail.setBcc(bcc);//密送人
389                 }
390                 t482101HEntityList.add(mail);
7caeae 391             }
X 392             if (t482101HEntityList.size() > 0) {
18553a 393                 String docCodeList = mailIfc.saveReceivingMailList(t482101HEntityList);//保存
3b74e3 394 //                mailAccountIfc.updateEmailTime(email.getAccountId());//更新一次配置
X 395
396                 if(hasPush) {//是否推送消息
397                     //发送通知(极光和webscoket)
398                     //取用户的手机号
399                     BaseService baseService = (BaseService) FactoryBean.getBean("BaseService");
400                     String tel = baseService.getJdbcTemplate().queryForObject("select tel  from    _sys_LoginUser where usercode=" + GridUtils.prossSqlParm(foundation.getUserCode()), String.class);
401                     MailPush.pushEmailInfo(t482101HEntityList, docCodeList, foundation.getDbId(), tel);
402                 }
7caeae 403             }
X 404         } catch (Exception e) {
405             throw e;
406         }
407     }
408
409     /**
410      * @param mimeMultipart 邮箱对象
411      * @param plainText     纯文本
412      * @param part          邮件附件集合
413      * @return
414      * @throws Exception
415      */
416     // 辅助方法,用于递归获取纯文本邮件内容
57c8bf 417     private String getTextFromMimeMultipart(MimeMultipart mimeMultipart, StringBuilder
b7ef4b 418             plainText, List<MailFileEntity.MailBodyPart> part, String unId, StringBuilder attachment, Integer dbId) throws Exception {
7caeae 419         int count = mimeMultipart.getCount();
X 420         if (count == 0) {
421             throw new MessagingException("Multipart with no body parts");
422         }
423         boolean multipartAlternative = isMultipartAlternative(mimeMultipart);
424         StringBuilder result = new StringBuilder();
425         if (multipartAlternative) {
426             for (int i = 0; i < count; i++) {
427                 BodyPart bodyPart = mimeMultipart.getBodyPart(i);
428                 if (bodyPart.isMimeType("text/plain")) {//这个是获取纯文本
429                     plainText.append(bodyPart.getContent());
430                 }
431                 if (bodyPart.isMimeType("text/html")) {//这个是获取html格式
432                     result.append(bodyPart.getContent());
433                 }
434             }
56d9f6 435             if (StringUtils.isBlank(result.toString())) {//没html时候把纯文本赋值过去
X 436                 result.append(plainText);
437             }
438         }
439 //        else {
7caeae 440             for (int i = 0; i < count; i++) {
X 441                 BodyPart bodyPart = mimeMultipart.getBodyPart(i);
56d9f6 442 //                if (bodyPart.isMimeType("text/html")) {//这个是获取html格式
X 443 //                    result.append(bodyPart.getContent());
444 //                }else
445                     if (bodyPart.isMimeType("image/*")) {//图片
7caeae 446                     MailFileEntity.MailBodyPart p = new MailFileEntity.MailBodyPart();
0c7568 447                     String fileName = "xxx.jpg";
X 448                     if (StringUtils.isNotBlank(bodyPart.getFileName())) {
449                         fileName = MimeUtility.decodeText(bodyPart.getFileName());
450                     }
7cf738 451                     p.setFileName(fileName);//有些邮件没有扩展名
7caeae 452                     String cId = ((IMAPBodyPart) bodyPart).getContentID();//获取cId
7cf738 453                     if (StringUtils.isNotBlank(cId)) {//在有扩展名时候
X 454                         if (cId.lastIndexOf(".") != -1) {
455                             p.setFileType(cId.substring(cId.lastIndexOf(".") + 1));
456                             p.setFileName(cId);//有些邮件没有扩展名
457                         }
458                     }
0c7568 459                     if (StringUtils.isBlank(p.getFileType())) {
7cf738 460                         if (fileName.lastIndexOf(".") != -1) {
X 461                             p.setFileType(fileName.substring(fileName.lastIndexOf(".") + 1));
462                         }
463                     }
7caeae 464                     p.setFileSize(bodyPart.getSize());
7cf738 465                     p.setByteFile(convertInputStreamToByteArray(bodyPart.getInputStream()));
X 466                     String fieldId = UUID.randomUUID().toString();//系统自定义一个随机字段
467                     p.setFieldId(fieldId);
7caeae 468                     String nextResult = result.toString();
X 469                     if (nextResult.contains(cId)) {//有嵌套内容
470                         //替换
b7ef4b 471                         nextResult = nextResult.replace("cid:" + cId + "", shoppingImageServer + "/uploads/email/" + dbId + "/482101/" + unId + "@p@" + p.getPhysicalFile());
7caeae 472                         result.setLength(0);//清空先
X 473                         result.append(nextResult);
474                     }
7cf738 475                     part.add(p);
7caeae 476                 } else if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {//附件
X 477                     MailFileEntity.MailBodyPart p = new MailFileEntity.MailBodyPart();
0c7568 478                     String fileName = "";
X 479                     if (StringUtils.isNotBlank(bodyPart.getFileName())) {
480                         fileName = MimeUtility.decodeText(bodyPart.getFileName());
481                     }
7cf738 482                     p.setFileName(fileName);
X 483                     if (StringUtils.isNotBlank(fileName)) {
484                         p.setFileType(fileName.substring(fileName.lastIndexOf(".") + 1));
485                     }
7caeae 486                     p.setFileSize(bodyPart.getSize());
7cf738 487                     p.setByteFile(convertInputStreamToByteArray(bodyPart.getInputStream()));
X 488                     String fieldId = UUID.randomUUID().toString();//系统自定义一个随机字段
489                     p.setFieldId(fieldId);
490                     attachment.append(";" + fieldId);
7caeae 491                     part.add(p);
X 492                 } else if (bodyPart.isMimeType("multipart/*")) {
b7ef4b 493                     result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent(), plainText, part, unId, attachment, dbId));
7caeae 494                 }
X 495             }
56d9f6 496 //        }
7caeae 497         return result.toString();
X 498     }
499
500     /**
501      * 辅助方法,判断是否为multipart/alternative类型的邮件
502      *
503      * @param mimeMultipart
504      * @return
505      * @throws Exception
506      */
507     private boolean isMultipartAlternative(MimeMultipart mimeMultipart) throws Exception {
508         boolean textPlainFound = false;
509         boolean textHtmlFound = false;
510         int count = mimeMultipart.getCount();
511         for (int i = 0; i < count; i++) {
512             BodyPart bodyPart = mimeMultipart.getBodyPart(i);
513             if (bodyPart.isMimeType("text/plain")) {
514                 textPlainFound = true;
515             } else if (bodyPart.isMimeType("text/html")) {
516                 textHtmlFound = true;
517             }
518         }
658898 519         return textPlainFound || textHtmlFound;
7caeae 520     }
X 521
522     /**
523      * 转换 byte
524      *
525      * @param inputStream
526      * @return
527      * @throws IOException
528      */
529     private byte[] convertInputStreamToByteArray(InputStream inputStream) throws IOException {
530         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
531         byte[] buffer = new byte[1024];
532         int length;
533         while ((length = inputStream.read(buffer)) != -1) {
534             byteArrayOutputStream.write(buffer, 0, length);
535         }
536         return byteArrayOutputStream.toByteArray();
537     }
538 }