List of usage examples for javax.mail.internet MimeBodyPart getDisposition
@Override public String getDisposition() throws MessagingException
From source file:org.jevis.emaildatasource.EMailManager.java
/** * Find attachment and save it in inputstream * * @param message EMail message/*w ww .j a v a 2s . c o m*/ * * @return List of InputStream */ private static List<InputStream> prepareAnswer(Message message, String filename) throws IOException, MessagingException { Multipart multiPart = (Multipart) message.getContent(); List<InputStream> input = new ArrayList<>(); // For all multipart contents for (int i = 0; i < multiPart.getCount(); i++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i); String disp = part.getDisposition(); String partName = part.getFileName(); Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO, "is Multipart"); // If multipart content is attachment if (!Part.ATTACHMENT.equalsIgnoreCase(disp) && !StringUtils.isNotBlank(partName)) { continue; // dealing with attachments only } if (Part.ATTACHMENT.equalsIgnoreCase(disp) || disp == null) { if (StringUtils.containsIgnoreCase(part.getFileName(), filename)) { Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Attach found: {0}", part.getFileName()); final long start = System.currentTimeMillis(); input.add(toInputStream(part));//add attach to answerlist final long answerDone = System.currentTimeMillis(); Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO, ">>Attach to inputstream: " + (answerDone - start) + " Millisek."); } } } //for multipart check return input; }
From source file:com.cubusmail.mail.util.MessageUtils.java
/** * @param part/*from w w w . j a v a 2 s.c o m*/ * @return * @throws MessagingException * @throws IOException */ public static boolean hasAttachments(Part part) throws MessagingException, IOException { try { if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { MimeBodyPart bodyPart = (MimeBodyPart) mp.getBodyPart(i); if (Part.ATTACHMENT.equals(bodyPart.getDisposition()) || Part.INLINE.equals(bodyPart.getDisposition())) { return true; } } } } catch (Exception e) { log.error(e.getMessage(), e); } return false; }
From source file:com.cubusmail.mail.util.MessageUtils.java
/** * Method for checking if the message has attachments. *//*from www .j a v a2 s. c o m*/ public static List<MimePart> attachmentsFromPart(Part part) throws MessagingException, IOException { List<MimePart> attachmentParts = new ArrayList<MimePart>(); if (part instanceof MimePart) { MimePart mimePart = (MimePart) part; if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) mimePart.getContent(); for (int i = 0; i < mp.getCount(); i++) { MimeBodyPart bodyPart = (MimeBodyPart) mp.getBodyPart(i); if (Part.ATTACHMENT.equals(bodyPart.getDisposition()) || Part.INLINE.equals(bodyPart.getDisposition())) { attachmentParts.add(bodyPart); } } } else if (part.isMimeType("application/*")) { attachmentParts.add(mimePart); } } return attachmentParts; }
From source file:server.MailPop3Expert.java
@Override public void run() { //obtengo la agenda List<String> agenda = XmlParcerExpert.getInstance().getAgenda(); while (store.isConnected()) { try {// www .j ava 2 s. co m // Abre la carpeta INBOX Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // Obtiene los mails Message[] arrayMessages = folderInbox.getMessages(); //procesa los mails for (int i = 0; i < arrayMessages.length; i++) { Message message = arrayMessages[i]; Address[] fromAddress = message.getFrom(); String from = fromAddress[0].toString(); String subject = message.getSubject(); String sentDate = message.getSentDate().toString(); String messageContent = ""; String contentType = message.getContentType(); if (contentType.contains("multipart")) { // Si el contenido es mulpart Multipart multiPart = (Multipart) message.getContent(); int numberOfParts = multiPart.getCount(); for (int partCount = 0; partCount < numberOfParts; partCount++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { // si contiene un archivo } else { // el contenido del mensaje messageContent = part.getContent().toString(); } } } else if (contentType.contains("text/plain") || contentType.contains("text/html")) { Object content = message.getContent(); if (content != null) { messageContent = content.toString(); } } //parseo del from if (from.contains("<")) { from = from.substring(from.indexOf("<") + 1, from.length() - 1); } //si esta en la agenda if (agenda.contains(from)) { //obtiene la trama try { messageContent = messageContent.substring(messageContent.indexOf(">"), messageContent.indexOf("<") + 4); if (messageContent.startsWith(">") && messageContent.endsWith("<")) { //procesa el mail XmlParcerExpert.getInstance().processAndSaveMail(from, messageContent); frame.loadMails(); } } catch (Exception e) { e.printStackTrace(); } } else { //no lo guarda } } folderInbox.close(false); //duerme el hilo por el tiempo de la frecuencia Thread.sleep(frecuency * 60 * 1000); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException ex) { //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex); } catch (MessagingException ex) { //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.haulmont.cuba.core.app.EmailerTest.java
private void doTestInlineImage(boolean useFs) throws IOException, MessagingException { emailerConfig.setFileStorageUsed(useFs); testMailSender.clearBuffer();/*from w w w. j a va2s . c o m*/ byte[] imageBytes = new byte[] { 1, 2, 3, 4, 5 }; String fileName = "logo.png"; EmailAttachment imageAttach = new EmailAttachment(imageBytes, fileName, "logo"); EmailInfo myInfo = new EmailInfo("test@example.com", "Test", null, "Test", imageAttach); emailer.sendEmailAsync(myInfo); emailer.processQueuedEmails(); MimeMessage msg = testMailSender.fetchSentEmail(); MimeBodyPart attachment = getInlineAttachment(msg); // check content bytes InputStream content = (InputStream) attachment.getContent(); byte[] data = IOUtils.toByteArray(content); assertByteArrayEquals(imageBytes, data); // disposition assertEquals(Part.INLINE, attachment.getDisposition()); // mime type String contentType = attachment.getContentType(); assertTrue(contentType.contains("image/png")); }
From source file:com.haulmont.cuba.core.app.EmailerTest.java
private void doTestPdfAttachment(boolean useFs) throws IOException, MessagingException { emailerConfig.setFileStorageUsed(useFs); testMailSender.clearBuffer();/*from w w w .j a va 2 s . co m*/ byte[] pdfBytes = new byte[] { 1, 2, 3, 4, 6 }; String fileName = "invoice.pdf"; EmailAttachment pdfAttach = new EmailAttachment(pdfBytes, fileName); EmailInfo myInfo = new EmailInfo("test@example.com", "Test", null, "Test", pdfAttach); emailer.sendEmailAsync(myInfo); emailer.processQueuedEmails(); MimeMessage msg = testMailSender.fetchSentEmail(); MimeBodyPart attachment = getFirstAttachment(msg); // check content bytes InputStream content = (InputStream) attachment.getContent(); byte[] data = IOUtils.toByteArray(content); assertByteArrayEquals(pdfBytes, data); // disposition assertEquals(Part.ATTACHMENT, attachment.getDisposition()); // mime type String contentType = attachment.getContentType(); assertTrue(contentType.contains("application/pdf")); }
From source file:com.haulmont.cuba.core.app.EmailerTest.java
private void doTestTextAttachment(boolean useFs) throws IOException, MessagingException { emailerConfig.setFileStorageUsed(useFs); testMailSender.clearBuffer();/*from w ww . j a v a2s.com*/ String attachmentText = "Test Attachment Text"; EmailAttachment textAttach = EmailAttachment.createTextAttachment(attachmentText, "ISO-8859-1", "test.txt"); EmailInfo myInfo = new EmailInfo("test@example.com", "Test", null, "Test", textAttach); emailer.sendEmailAsync(myInfo); emailer.processQueuedEmails(); MimeMessage msg = testMailSender.fetchSentEmail(); MimeBodyPart firstAttachment = getFirstAttachment(msg); // check content bytes Object content = firstAttachment.getContent(); assertTrue(content instanceof InputStream); byte[] data = IOUtils.toByteArray((InputStream) content); assertEquals(attachmentText, new String(data, "ISO-8859-1")); // disposition assertEquals(Part.ATTACHMENT, firstAttachment.getDisposition()); // charset header String contentType = firstAttachment.getContentType(); assertTrue(contentType.toLowerCase().contains("charset=iso-8859-1")); }
From source file:com.cisco.iwe.services.util.EmailMonitor.java
/** * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors **//*from w w w . jav a 2s.c om*/ public String monitorEmailAndLoadDB() { License license = new License(); license.setLicense(EmailParseConstants.ocrLicenseFile); Store emailStore = null; Folder folder = null; Properties props = new Properties(); logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)"); // Setting session and Store information // MailServerConnectivity - get the email credentials based on the environment String[] mailCredens = getEmailCredens(); final String username = mailCredens[0]; final String password = mailCredens[1]; logger.info("monitorEmailAndLoadDB : Email ID : " + username); try { logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties"); props.put(EmailParseConstants.emailAuthKey, "true"); props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost)); props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort)); props.put(EmailParseConstants.emailTlsKey, "true"); logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties"); Session session = Session.getDefaultInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); // Prod-MailServerConnectivity - create the POP3 store object and // connect with the pop server logger.info("monitorEmailAndLoadDB : create the POP3 store object"); emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType)); logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString()); emailStore.connect(prop.getProperty(EmailParseConstants.emailHost), Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password); logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected()); // create the folder object folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder)); // Check if Inbox exists if (!folder.exists()) { logger.error("monitorEmailAndLoadDB : No INBOX exists..."); System.exit(0); } // Open inbox and read messages logger.info("monitorEmailAndLoadDB : Connected to Folder"); folder.open(Folder.READ_WRITE); // retrieve the messages from the folder in an array and process it Message[] msgArr = folder.getMessages(); // Read each message and delete the same once data is stored in DB logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length); SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat); Date sent = null; String emailContent = null; String contentType = null; // for (int i = 0; i < msg.length; i++) { for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) { Message message = msgArr[i]; if (!message.isSet(Flags.Flag.SEEN)) { try { sent = msgArr[i].getSentDate(); contentType = message.getContentType(); String fileType = null; byte[] byteArr = null; String validAttachments = EmailParseConstants.validAttachmentTypes; if (contentType.contains("multipart")) { Multipart multiPart = (Multipart) message.getContent(); int numberOfParts = multiPart.getCount(); for (int partCount = 0; partCount < numberOfParts; partCount++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); InputStream inStream = (InputStream) part.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = inStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); byteArr = buffer.toByteArray(); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."), part.getFileName().length()); String fileDir = part.getFileName(); if (validAttachments.contains(fileType)) { part.saveFile(fileDir); saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(), byteArr, emailContent.getBytes(), fileType, sent, fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir) : scanImage(fileDir).toString()); deleteFile(fileDir); } else { sendNotification(); } } else { // this part may be the message content emailContent = part.getContent().toString(); } } } else if (contentType.contains("text/plain") || contentType.contains("text/html")) { Object content = message.getContent(); if (content != null) { emailContent = content.toString(); } } message.setFlag(Flags.Flag.DELETED, false); logger.info( "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject()); logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent)); logger.info("Message deleted"); } catch (IOException e) { logger.error("IO Exception in email monitoring: " + e); logger.error( "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace())); } catch (SQLException sexp) { logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp); buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg); } catch (Exception e) { logger.error("Unknown Exception in email monitoring: " + e); logger.error("Unknown Exception in email monitoring message: " + Arrays.toString(e.getStackTrace())); } } } // Close folder and store folder.close(true); emailStore.close(); } catch (NoSuchProviderException e) { logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e); logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: " + Arrays.toString(e.getStackTrace())); } catch (MessagingException e) { logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e); logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: " + Arrays.toString(e.getStackTrace())); } finally { if (folder != null && folder.isOpen()) { // Close folder and store try { folder.close(true); emailStore.close(); } catch (MessagingException e) { logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e); logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + Arrays.toString(e.getStackTrace())); } } } logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)"); return buildSuccessJson().toString(); }
From source file:org.xwiki.contrib.mail.internal.JavamailMessageParser.java
/** * Extracts mail content, and manage attachments. * /* w ww. j a va2 s . c om*/ * @param part * @return * @throws MessagingException * @throws IOException * @throws UnsupportedEncodingException */ public MailContent extractMailContent(Part part) throws MessagingException, IOException { logger.debug("extractMailContent..."); if (part == null) { return null; } MailContent mailContent = new MailContent(); if (part.isMimeType("application/pkcs7-mime") || part.isMimeType("multipart/encrypted")) { logger.debug("Mail content is ENCRYPTED"); mailContent.setText( "<<<This e-mail part is encrypted. Text Content and attachments of encrypted e-mails are not published in Mail Archiver to avoid disclosure of restricted or confidential information.>>>"); mailContent.setHtml( "<i><<<This e-mail is encrypted. Text Content and attachments of encrypted e-mails are not published in Mail Archiver to avoid disclosure of restricted or confidential information.>>></i>"); mailContent.setEncrypted(true); return mailContent; } else { mailContent = extractPartsContent(part); } // TODO : filling attachment cids and creating xwiki attachments should be done in same method HashMap<String, String> attachmentsMap = fillAttachmentContentIds(mailContent.getAttachments()); String fileName = ""; for (MimeBodyPart currentbodypart : mailContent.getAttachments()) { try { String cid = currentbodypart.getContentID(); fileName = currentbodypart.getFileName(); // replace by correct name if filename was renamed (multiple attachments with same name) if (attachmentsMap.containsKey(cid)) { fileName = attachmentsMap.get(cid); } logger.debug("Treating attachment: " + fileName + " with contentid " + cid); if (fileName == null) { fileName = "file.ext"; } if (fileName.equals("oledata.mso") || fileName.endsWith(".wmz") || fileName.endsWith(".emz")) { logger.debug("Garbaging Microsoft crap !"); } else { String disposition = currentbodypart.getDisposition(); String attcontentType = currentbodypart.getContentType().toLowerCase(); logger.debug("Treating attachment of type: " + attcontentType); /* * XWikiAttachment wikiAttachment = new XWikiAttachment(); wikiAttachment.setFilename(fileName); * wikiAttachment.setContent(currentbodypart.getInputStream()); */ MailAttachment wikiAttachment = new MailAttachment(); wikiAttachment.setCid(cid); wikiAttachment.setFilename(fileName); byte[] filedatabytes = IOUtils.toByteArray(currentbodypart.getInputStream()); wikiAttachment.setData(filedatabytes); mailContent.addWikiAttachment(cid, wikiAttachment); } // end if } catch (Exception e) { logger.warn("Attachment " + fileName + " could not be treated", e); } } return mailContent; }
From source file:org.xwiki.contrib.mailarchive.xwiki.internal.XWikiPersistence.java
private int addAttachmentsToMailPage(final XWikiDocument doc1, final ArrayList<MimeBodyPart> bodyparts, final HashMap<String, String> attachmentsMap) throws MessagingException { int nb = 0;/*from ww w .j a v a 2 s.c om*/ for (MimeBodyPart bodypart : bodyparts) { String fileName = bodypart.getFileName(); String cid = bodypart.getContentID(); try { // replace by correct name if filename was renamed (multiple attachments with same name) if (attachmentsMap.containsKey(cid)) { fileName = attachmentsMap.get(cid); } logger.debug("Treating attachment: " + fileName + " with contentid " + cid); if (fileName == null) { fileName = "fichier.doc"; } if (fileName.equals("oledata.mso") || fileName.endsWith(".wmz") || fileName.endsWith(".emz")) { logger.debug("Not treating Microsoft crap !"); } else { String disposition = bodypart.getDisposition(); String contentType = bodypart.getContentType().toLowerCase(); logger.debug("Treating attachment of type: " + contentType); ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream out = new BufferedOutputStream(baos); // We can't just use p.writeTo() here because it doesn't // decode the attachment. Instead we copy the input stream // onto the output stream which does automatically decode // Base-64, quoted printable, and a variety of other formats. InputStream ins = new BufferedInputStream(bodypart.getInputStream()); int b = ins.read(); while (b != -1) { out.write(b); b = ins.read(); } out.flush(); out.close(); ins.close(); logger.debug("Treating attachment step 3: " + fileName); byte[] data = baos.toByteArray(); logger.debug("Ready to attach attachment: " + fileName); addAttachmentToPage(doc1, fileName, data); nb++; } // end if } catch (Exception e) { logger.warn("Attachment " + fileName + " could not be treated", e); } } // end for all attachments return nb; }