List of usage examples for javax.mail BodyPart getDisposition
public String getDisposition() throws MessagingException;
From source file:net.prhin.mailman.MailMan.java
public static void main(String[] args) { Properties props = new Properties(); props.setProperty(resourceBundle.getString("mailman.mail.store"), resourceBundle.getString("mailman.protocol")); Session session = Session.getInstance(props); try {/*w w w . j a v a 2s. c o m*/ Store store = session.getStore(); store.connect(resourceBundle.getString("mailman.host"), resourceBundle.getString("mailman.user"), resourceBundle.getString("mailman.password")); Folder inbox = store.getFolder(resourceBundle.getString("mailman.folder")); inbox.open(Folder.READ_ONLY); inbox.getUnreadMessageCount(); Message[] messages = inbox.getMessages(); for (int i = 0; i <= messages.length / 2; i++) { Message tmpMessage = messages[i]; Multipart multipart = (Multipart) tmpMessage.getContent(); System.out.println("Multipart count: " + multipart.getCount()); for (int j = 0; j < multipart.getCount(); j++) { BodyPart bodyPart = multipart.getBodyPart(j); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) { if (bodyPart.getContent().getClass().equals(MimeMultipart.class)) { MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent(); for (int k = 0; k < mimeMultipart.getCount(); k++) { if (mimeMultipart.getBodyPart(k).getFileName() != null) { printFileContents(mimeMultipart.getBodyPart(k)); } } } } else { printFileContents(bodyPart); } } } inbox.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:Main.java
public static boolean isContainAttachment(Part part) throws MessagingException, IOException { boolean flag = false; if (part.isMimeType("multipart/*")) { MimeMultipart multipart = (MimeMultipart) part.getContent(); int partCount = multipart.getCount(); for (int i = 0; i < partCount; i++) { BodyPart bodyPart = multipart.getBodyPart(i); String disp = bodyPart.getDisposition(); if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { flag = true;/*w w w . j av a 2 s.c om*/ } else if (bodyPart.isMimeType("multipart/*")) { flag = isContainAttachment(bodyPart); } else { String contentType = bodyPart.getContentType(); if (contentType.indexOf("application") != -1) { flag = true; } if (contentType.indexOf("name") != -1) { flag = true; } } if (flag) break; } } else if (part.isMimeType("message/rfc822")) { flag = isContainAttachment((Part) part.getContent()); } return flag; }
From source file:com.mgmtp.jfunk.core.mail.MessageUtils.java
private static void parseMultipart(final StrBuilder sb, final Multipart multipart) throws MessagingException, IOException { for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); String disposition = bodyPart.getDisposition(); if (disposition == null && bodyPart instanceof MimeBodyPart) { // not an attachment MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart; if (mimeBodyPart.getContent() instanceof Multipart) { parseMultipart(sb, (Multipart) mimeBodyPart.getContent()); } else { String body = (String) mimeBodyPart.getContent(); sb.appendln(body);//from www. j av a 2 s. c om sb.appendln(""); } } } }
From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java
public static List<Attachment> getMessageAttachments(MimeMessage message) { List<Attachment> attachments = new LinkedList<>(); try {// w w w . j a va2 s . c o m Multipart multipartMessage = (Multipart) message.getContent(); for (int i = 0; i < multipartMessage.getCount(); i++) { BodyPart bodyPart = multipartMessage.getBodyPart(i); if (bodyPart.getDisposition() != null && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) { byte[] content = IOUtils.toByteArray(bodyPart.getInputStream()); attachments.add(new Attachment(bodyPart.getContentType(), bodyPart.getFileName(), Base64.encodeBase64String(content))); } } } catch (Exception e) { // do nothing } return attachments; }
From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java
public static Body getMessageBody(MimeMessage message, String mimeType) { try {//from w ww. j av a2 s . c o m if (message.getContent() instanceof Multipart) { Multipart multipartMessage = (Multipart) message.getContent(); for (int i = 0; i < multipartMessage.getCount(); i++) { BodyPart bodyPart = multipartMessage.getBodyPart(i); if (bodyPart.isMimeType(mimeType) && (Part.INLINE.equalsIgnoreCase(bodyPart.getDisposition()) || Objects.isNull(bodyPart.getDisposition()))) { return new Body(bodyPart.getContentType(), bodyPart.getContent().toString()); } } } else { return new Body(message.getContentType(), message.getContent().toString()); } } catch (Exception e) { // do nothing } return null; }
From source file:org.elasticsearch.river.email.EmailToJson.java
public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException { if (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart) part.getContent(); int partCount = multipart.getCount(); for (int i = 0; i < partCount; i++) { BodyPart bodyPart = multipart.getBodyPart(i); String disp = bodyPart.getDisposition(); if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { InputStream is = bodyPart.getInputStream(); saveFile(is, destDir, decodeText(bodyPart.getFileName())); } else if (bodyPart.isMimeType("multipart/*")) { saveAttachment(bodyPart, destDir); } else { String contentType = bodyPart.getContentType(); if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName())); }//www . j av a 2 s . c o m } } } else if (part.isMimeType("message/rfc822")) { saveAttachment((Part) part.getContent(), destDir); } }
From source file:org.elasticsearch.river.email.EmailToJson.java
public static List<AttachmentInfo> saveAttachmentToWeedFs(Part message, List<AttachmentInfo> attachments, EmailRiverConfig config)/*from w ww . j a va2 s . c o m*/ throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException { if (attachments == null) { attachments = new ArrayList<AttachmentInfo>(); } boolean hasAttachment = false; try { hasAttachment = isContainAttachment(message); } catch (MessagingException e) { logger.error("save attachment", e); } catch (IOException e) { logger.error("save attachment", e); } if (hasAttachment) { if (message.isMimeType("multipart/*")) { Multipart multipart = (Multipart) message.getContent(); int partCount = multipart.getCount(); for (int i = 0; i < partCount; i++) { BodyPart bodyPart = multipart.getBodyPart(i); String disp = bodyPart.getDisposition(); if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { InputStream is = bodyPart.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len = -1; while ((len = bis.read()) != -1) { bos.write(len); } bos.close(); bis.close(); byte[] data = bos.toByteArray(); String fileId = uploadFileToWeedfs(data, config); if (fileId != null) { AttachmentInfo info = new AttachmentInfo(); info.fileId = fileId; info.fileName = decodeText(bodyPart.getFileName()); info.fileSize = data.length; attachments.add(info); } } else if (bodyPart.isMimeType("multipart/*")) { attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config)); } else { String contentType = bodyPart.getContentType(); if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config)); } } } } else if (message.isMimeType("message/rfc822")) { attachments.addAll(saveAttachmentToWeedFs(message, attachments, config)); } } return attachments; }
From source file:com.cws.esolutions.core.utils.EmailUtils.java
/** * Processes and sends an email message as generated by the requesting * application. This method is utilized with a JNDI datasource. * * @param dataSource - The email message * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise * @param authList - If authRequired is true, this must be populated with the auth info * @return List - The list of email messages in the mailstore * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing *///w w w . ja v a 2s .c om public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException { final String methodName = EmailUtils.CNAME + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("dataSource: {}", dataSource); DEBUGGER.debug("authRequired: {}", authRequired); DEBUGGER.debug("authList: {}", authList); } Folder mailFolder = null; Session mailSession = null; Folder archiveFolder = null; List<EmailMessage> emailMessages = null; Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -24); final Long TIME_PERIOD = cal.getTimeInMillis(); final URLName URL_NAME = (authRequired) ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1)) : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, null, null); if (DEBUG) { DEBUGGER.debug("timePeriod: {}", TIME_PERIOD); DEBUGGER.debug("URL_NAME: {}", URL_NAME); } try { // Set up mail session mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator()) : Session.getDefaultInstance(dataSource); if (DEBUG) { DEBUGGER.debug("mailSession: {}", mailSession); } if (mailSession == null) { throw new MessagingException("Unable to configure email services"); } mailSession.setDebug(DEBUG); Store mailStore = mailSession.getStore(URL_NAME); mailStore.connect(); if (DEBUG) { DEBUGGER.debug("mailStore: {}", mailStore); } if (!(mailStore.isConnected())) { throw new MessagingException("Failed to connect to mail service. Cannot continue."); } mailFolder = mailStore.getFolder("inbox"); archiveFolder = mailStore.getFolder("archive"); if (!(mailFolder.exists())) { throw new MessagingException("Requested folder does not exist. Cannot continue."); } mailFolder.open(Folder.READ_WRITE); if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) { throw new MessagingException("Failed to open requested folder. Cannot continue"); } if (!(archiveFolder.exists())) { archiveFolder.create(Folder.HOLDS_MESSAGES); } Message[] mailMessages = mailFolder.getMessages(); if (mailMessages.length == 0) { throw new MessagingException("No messages were found in the provided store."); } emailMessages = new ArrayList<EmailMessage>(); for (Message message : mailMessages) { if (DEBUG) { DEBUGGER.debug("MailMessage: {}", message); } // validate the message here String messageId = message.getHeader("Message-ID")[0]; Long messageDate = message.getReceivedDate().getTime(); if (DEBUG) { DEBUGGER.debug("messageId: {}", messageId); DEBUGGER.debug("messageDate: {}", messageDate); } // only get emails for the last 24 hours // this should prevent us from pulling too // many emails if (messageDate >= TIME_PERIOD) { // process it Multipart attachment = (Multipart) message.getContent(); Map<String, InputStream> attachmentList = new HashMap<String, InputStream>(); for (int x = 0; x < attachment.getCount(); x++) { BodyPart bodyPart = attachment.getBodyPart(x); if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) { continue; } attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream()); } List<String> toList = new ArrayList<String>(); List<String> ccList = new ArrayList<String>(); List<String> bccList = new ArrayList<String>(); List<String> fromList = new ArrayList<String>(); for (Address from : message.getFrom()) { fromList.add(from.toString()); } if ((message.getRecipients(RecipientType.TO) != null) && (message.getRecipients(RecipientType.TO).length != 0)) { for (Address to : message.getRecipients(RecipientType.TO)) { toList.add(to.toString()); } } if ((message.getRecipients(RecipientType.CC) != null) && (message.getRecipients(RecipientType.CC).length != 0)) { for (Address cc : message.getRecipients(RecipientType.CC)) { ccList.add(cc.toString()); } } if ((message.getRecipients(RecipientType.BCC) != null) && (message.getRecipients(RecipientType.BCC).length != 0)) { for (Address bcc : message.getRecipients(RecipientType.BCC)) { bccList.add(bcc.toString()); } } EmailMessage emailMessage = new EmailMessage(); emailMessage.setMessageTo(toList); emailMessage.setMessageCC(ccList); emailMessage.setMessageBCC(bccList); emailMessage.setEmailAddr(fromList); emailMessage.setMessageAttachments(attachmentList); emailMessage.setMessageDate(message.getSentDate()); emailMessage.setMessageSubject(message.getSubject()); emailMessage.setMessageBody(message.getContent().toString()); emailMessage.setMessageSources(message.getHeader("Received")); if (DEBUG) { DEBUGGER.debug("emailMessage: {}", emailMessage); } emailMessages.add(emailMessage); if (DEBUG) { DEBUGGER.debug("emailMessages: {}", emailMessages); } } // archive it archiveFolder.open(Folder.READ_WRITE); if (archiveFolder.isOpen()) { mailFolder.copyMessages(new Message[] { message }, archiveFolder); message.setFlag(Flags.Flag.DELETED, true); } } } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } catch (MessagingException mex) { throw new MessagingException(mex.getMessage(), mex); } finally { try { if ((mailFolder != null) && (mailFolder.isOpen())) { mailFolder.close(true); } if ((archiveFolder != null) && (archiveFolder.isOpen())) { archiveFolder.close(false); } } catch (MessagingException mx) { ERROR_RECORDER.error(mx.getMessage(), mx); } } return emailMessages; }
From source file:mx.uaq.facturacion.enlace.EmailParserUtils.java
/** * Parses any {@link Multipart} instances that contain text or Html attachments, * {@link InputStream} instances, additional instances of {@link Multipart} * or other attached instances of {@link javax.mail.Message}. * * Will create the respective {@link EmailFragment}s representing those attachments. * * Instances of {@link javax.mail.Message} are delegated to * {@link #handleMessage(File, javax.mail.Message, List)}. Further instances * of {@link Multipart} are delegated to * {@link #handleMultipart(File, Multipart, javax.mail.Message, List)}. * * @param directory Must not be null/*from w w w. j a v a 2 s. c om*/ * @param multipart Must not be null * @param mailMessage Must not be null * @param emailFragments Must not be null */ public static void handleMultipart(File directory, Multipart multipart, javax.mail.Message mailMessage, List<EmailFragment> emailFragments) { Assert.notNull(directory, "The directory must not be null."); Assert.notNull(multipart, "The multipart object to be parsed must not be null."); Assert.notNull(mailMessage, "The mail message to be parsed must not be null."); Assert.notNull(emailFragments, "The collection of emailfragments must not be null."); final int count; try { count = multipart.getCount(); if (LOGGER.isInfoEnabled()) { LOGGER.info(String.format("Number of enclosed BodyPart objects: %s.", count)); } } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving the number of enclosed BodyPart objects.", e); } for (int i = 0; i < count; i++) { final BodyPart bp; try { bp = multipart.getBodyPart(i); } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving body part.", e); } final String contentType; String filename; final String disposition; final String subject; try { contentType = bp.getContentType(); filename = bp.getFileName(); disposition = bp.getDisposition(); subject = mailMessage.getSubject(); if (filename == null && bp instanceof MimeBodyPart) { filename = ((MimeBodyPart) bp).getContentID(); } } catch (MessagingException e) { throw new IllegalStateException("Unable to retrieve body part meta data.", e); } if (LOGGER.isInfoEnabled()) { LOGGER.info(String.format( "BodyPart - Content Type: '%s', filename: '%s', disposition: '%s', subject: '%s'", new Object[] { contentType, filename, disposition, subject })); } if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) { LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType)); } final Object content; try { content = bp.getContent(); } catch (IOException e) { throw new IllegalStateException("Error while retrieving the email contents.", e); } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving the email contents.", e); } if (content instanceof String) { if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) { emailFragments.add(new EmailFragment(directory, i + "-" + filename, content)); LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType)); } else { final String textFilename; final ContentType ct; try { ct = new ContentType(contentType); } catch (ParseException e) { throw new IllegalStateException("Error while parsing content type '" + contentType + "'.", e); } if ("text/plain".equalsIgnoreCase(ct.getBaseType())) { textFilename = "message.txt"; } else if ("text/html".equalsIgnoreCase(ct.getBaseType())) { textFilename = "message.html"; } else { textFilename = "message.other"; } emailFragments.add(new EmailFragment(directory, textFilename, content)); } } else if (content instanceof InputStream) { final InputStream inputStream = (InputStream) content; final ByteArrayOutputStream bis = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, bis); } catch (IOException e) { throw new IllegalStateException( "Error while copying input stream to the ByteArrayOutputStream.", e); } emailFragments.add(new EmailFragment(directory, filename, bis.toByteArray())); } else if (content instanceof javax.mail.Message) { handleMessage(directory, (javax.mail.Message) content, emailFragments); } else if (content instanceof Multipart) { final Multipart mp2 = (Multipart) content; handleMultipart(directory, mp2, mailMessage, emailFragments); } else { throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName()); } } }
From source file:de.saly.elasticsearch.support.IndexableMailMessage.java
public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent, final boolean withAttachments, final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException { final IndexableMailMessage im = new IndexableMailMessage(); @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = jmm.getAllHeaders(); final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>(); while (allHeaders.hasMoreElements()) { final Header h = allHeaders.nextElement(); headerList.add(new IndexableHeader(h.getName(), h.getValue())); }//w w w. j a v a2 s. c o m im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()])); im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields)); if (jmm.getFolder() instanceof POP3Folder) { im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm)); im.setMailboxType("POP"); } else { im.setMailboxType("IMAP"); } if (jmm.getFolder() instanceof UIDFolder) { im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm)); } im.setFolderFullName(jmm.getFolder().getFullName()); im.setFolderUri(jmm.getFolder().getURLName().toString()); im.setContentType(jmm.getContentType()); im.setSubject(jmm.getSubject()); im.setSize(jmm.getSize()); im.setSentDate(jmm.getSentDate()); if (jmm.getReceivedDate() != null) { im.setReceivedDate(jmm.getReceivedDate()); } if (jmm.getFrom() != null && jmm.getFrom().length > 0) { im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0])); } if (jmm.getRecipients(RecipientType.TO) != null) { im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO))); } if (jmm.getRecipients(RecipientType.CC) != null) { im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC))); } if (jmm.getRecipients(RecipientType.BCC) != null) { im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC))); } if (withTextContent) { // try { String textContent = getText(jmm, 0); if (stripTags) { textContent = stripTags(textContent); } im.setTextContent(textContent); // } catch (final Exception e) { // logger.error("Unable to retrieve text content for message {} due to {}", // e, ((MimeMessage) jmm).getMessageID(), e); // } } if (withAttachments) { try { final Object content = jmm.getContent(); // look for attachments if (jmm.isMimeType("multipart/*") && content instanceof Multipart) { List<ESAttachment> attachments = new ArrayList<ESAttachment>(); final Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { final BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && !StringUtils.isNotBlank(bodyPart.getFileName())) { continue; // dealing with attachments only } final InputStream is = bodyPart.getInputStream(); final byte[] bytes = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName())); } if (!attachments.isEmpty()) { im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()])); im.setAttachmentCount(im.getAttachments().length); attachments.clear(); attachments = null; } } } catch (final Exception e) { logger.error( "Error indexing attachments (message will be indexed but without attachments) due to {}", e, e.toString()); } } im.setFlags(IMAPUtils.toStringArray(jmm.getFlags())); im.setFlaghashcode(jmm.getFlags().hashCode()); return im; }