Какое лучшее решение для загрузки вложения из Gmail и закодировать его? - PullRequest
0 голосов
/ 08 мая 2019

Я успешно реализовал загрузку вложений из серверной части gmail Java в Angular с помощью REST. Документ PDF занимает много времени для отображения.

это мой сервис для получения списка вложений:

 @Service
 public class DownloadAttachmentServiceImpl implements 
 DownloadAttachmentService {


 @Autowired
 private GmailConfig gmailConfig;

 @Autowired
 GuiEmailContactServiceDb guiEmailContactServiceDb;

@Autowired
 IAuthenticationFacade authenticationFacade;

@Autowired
DefAgencyService defAgencyService;

private Properties setPropertiesParams() {
  Properties properties = new Properties();
properties.put("mail.imap.socketFactory.class", 
this.gmailConfig.getSocketFactoryClass());
properties.put("mail.imap.host", this.gmailConfig.getHost());
properties.put("mail.imap.port", this.gmailConfig.getPort());
properties.put("mail.imap.starttls.enable", 
this.gmailConfig.getStarttlsEnable());
return properties;
}

@Override
public List<FileUploaded> downloadEmailAttachments(Timestamp fromDate, 
 Timestamp toDate) {
List<FileUploaded> fileUploadedList = new ArrayList<FileUploaded>();
String host = "imap.gmail.com";
DefAgency connectedAgency = this.authenticationFacade.getConnectedAgency();
Integer agencyId = connectedAgency.getAgencyId();
String email = this.defAgencyService.findOne(agencyId).getEmail();
String emailPassword =
    this.guiEmailContactServiceDb.findGuiEmailContactByAddressMail(email).getEmailPassword();
try {
  Session emailSession = Session.getDefaultInstance(this.setPropertiesParams());
  Store store = emailSession.getStore("imaps");
  store.connect(host, email, emailPassword);
  Folder emailFolder;
  emailFolder = store.getFolder("[Gmail]/Messages envoyés");
  if (emailFolder == null) {
    emailFolder = store.getFolder("[Gmail]/Sent Mail");
  }
  emailFolder.open(Folder.READ_ONLY);
  SearchTerm olderThan = null;
  SearchTerm newerThan = null;
  SearchTerm andTerm = searchMessageByDate(fromDate, toDate);
  Message[] messages = emailFolder.search(andTerm);

  for (Message message : messages) {
    String subject = message.getSubject();
    if (subject != null) {
      if (subject.equals("Scan de votre document")) {

        String contentType = message.getContentType();
        String attachFiles = "";
        String messageContent = "";
        if (contentType.contains("multipart")) {
          // content may contain attachments
          Multipart multiPart = (Multipart) message.getContent();
          int numberOfParts = multiPart.getCount();
          for (int partCount = 0; partCount < numberOfParts; partCount++) {

            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
            String disposition = part.getDisposition();
            if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
              InputStream inputStream = part.getInputStream();
              setFileUploaded(fileUploadedList, message, partCount, part, inputStream);
            } else {
              messageContent = part.getContent().toString();
            }
          }
          if (attachFiles.length() > 1) {
            attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
          }
        } else if (contentType.contains("text/plain") || 
 contentType.contains("text/html")) {
          Object content = message.getContent();
          if (content != null) {
            messageContent = content.toString();
          }
        }
      }

    }
  }
  emailFolder.close(false);
  store.close();
} catch (NoSuchProviderException ex) {
  logger.error("No provider for imap");
  ex.printStackTrace();
} catch (MessagingException ex) {
  logger.error("Could not connect to the message store");
  throw new Exception(ex);
} catch (IOException e) {
  e.printStackTrace();
} finally {
  return fileUploadedList;
}
}

private SearchTerm searchMessageByDate(Timestamp fromDate, Timestamp 
toDate) {
SearchTerm olderThan;
SearchTerm newerThan;
if (fromDate == null && toDate == null) {
  Date currentDate = DateUtils.truncate(new Date(), 
  Calendar.DAY_OF_MONTH);
  olderThan = new ReceivedDateTerm(ComparisonTerm.LT, 
  DateUtils.addDays(currentDate, 1));
  newerThan = new ReceivedDateTerm(ComparisonTerm.GT, 
DateUtils.addDays(currentDate, -1));
} else {
  Date dateStart = DateUtils.truncate(new Date(toDate.getTime()), 
  Calendar.DAY_OF_MONTH);
  Date toFinal = DateUtils.truncate(new Date(fromDate.getTime()), 
 Calendar.DAY_OF_MONTH);
  olderThan = new ReceivedDateTerm(ComparisonTerm.LT, dateStart);
  newerThan = new ReceivedDateTerm(ComparisonTerm.GT, toFinal);
}
SearchTerm andTerm = new AndTerm(olderThan, newerThan);  
return andTerm;
}

private void setFileUploaded(List<FileUploaded> fileUploadedList, 
Message 
message, int partCount,
  MimeBodyPart part, InputStream inputStream) throws MessagingException, 
IOException {
FileUploaded fileUploaded = new FileUploaded();
fileUploaded.setId(partCount);
fileUploaded.setAttachementMailName(part.getFileName());
fileUploaded.setDate(message.getReceivedDate());
fileUploaded.setFileType(part.getContentType());
byte[] fileData = IOUtils.toByteArray(inputStream);
String byteToString = Base64.getEncoder().encodeToString(fileData);
fileUploaded.setContent(byteToString);
fileUploaded.setSubject(message.getSubject());
fileUploadedList.add(fileUploaded);
}

}

для передней части. У меня есть это:

initImportEmailAttachmentList(from,to){
 return  this._attachmentHttpService.displayPdf(from, to).then((data 
 :any) 
 => {
   this.imageList= data;  
   this.importEmailAttachmentList=data;
  this.imageList.forEach(data=>{
    data.date = this.dateService.getUtcStringDate(new Date(data.date));      
    const byteArray = new 
  Uint8Array(atob(data.content).split('').map(char => 
  char.charCodeAt(0)));
    const blob = new Blob([byteArray], { type: 'application/pdf' });
    const  url = window.URL.createObjectURL(blob);
    data.pdfSrc=  url;     
    data.content= url; 
  }); 
  }); 
}

Моя проблема в том, как оптимизировать время моих услуг: получить только электронное письмо с указанной темой и датой?а также мой вопрос: это необходимо для кодирования моего pdf в base64 в java, отправки его на передний план и декодирования, а затем отображения его?

спасибо за помощь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...