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