List of usage examples for javax.mail BodyPart getContentType
public String getContentType() throws MessagingException;
From source file:net.fenyo.mail4hotspot.service.MailManager.java
public static void main(String[] args) throws NoSuchProviderException, MessagingException { System.out.println("Salut"); // trustSSL(); /* final Properties props = new Properties(); props.put("mail.smtp.host", "my-mail-server"); props.put("mail.from", "me@example.com"); javax.mail.Session session = javax.mail.Session.getInstance(props, null); try {/*from w ww . ja va 2 s. c o m*/ MimeMessage msg = new MimeMessage(session); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, "you@example.com"); msg.setSubject("JavaMail hello world example"); msg.setSentDate(new Date()); msg.setText("Hello, world!\n"); Transport.send(msg); } catch (MessagingException mex) { System.out.println("send failed, exception: " + mex); }*/ final Properties props = new Properties(); //props.put("mail.host", "10.69.60.6"); //props.put("mail.user", "fenyo"); //props.put("mail.from", "fenyo@fenyo.net"); //props.put("mail.transport.protocol", "smtps"); //props.put("mail.store.protocol", "pop3s"); // [javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], // javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], // javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], // javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], // javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], // javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc]] // final Provider[] providers = session.getProviders(); javax.mail.Session session = javax.mail.Session.getInstance(props, null); session.setDebug(true); //session.setDebug(false); // final Store store = session.getStore("pop3s"); // store.connect("10.69.60.6", 995, "fenyo", "PASSWORD"); // final Store store = session.getStore("imaps"); // store.connect("10.69.60.6", 993, "fenyo", "PASSWORD"); // System.out.println(store.getDefaultFolder().getMessageCount()); //final Store store = session.getStore("pop3"); final Store store = session.getStore("pop3s"); //final Store store = session.getStore("imaps"); // store.addStoreListener(new StoreListener() { // public void notification(StoreEvent e) { // String s; // if (e.getMessageType() == StoreEvent.ALERT) // s = "ALERT: "; // else // s = "NOTICE: "; // System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX: " + s + e.getMessage()); // } // }); //store.connect("10.69.60.6", 110, "fenyo", "PASSWORD"); store.connect("pop.gmail.com", 995, "alexandre.fenyo@gmail.com", "PASSWORD"); //store.connect("localhost", 110, "alexandre.fenyo@yahoo.com", "PASSWORD"); //store.connect("localhost", 995, "fenyo@live.fr", "PASSWORD"); //store.connect("localhost", 995, "thisisatestforalex@aol.fr", "PASSWORD"); // final Folder[] folders = store.getPersonalNamespaces(); // for (Folder f : folders) { // System.out.println("Folder: " + f.getMessageCount()); // final Folder g = f.getFolder("INBOX"); // g.open(Folder.READ_ONLY); // System.out.println(" g:" + g.getMessageCount()); // } final Folder inbox = store.getDefaultFolder().getFolder("INBOX"); inbox.open(Folder.READ_ONLY); System.out.println("nmessages: " + inbox.getMessageCount()); final Message[] messages = inbox.getMessages(); for (Message message : messages) { System.out.println("message:"); System.out.println(" size: " + message.getSize()); try { if (message.getFrom() != null) System.out.println(" From: " + message.getFrom()[0]); } catch (final Exception ex) { System.out.println(ex.toString()); } System.out.println(" content-type: " + message.getContentType()); System.out.println(" disposition: " + message.getDisposition()); System.out.println(" description: " + message.getDescription()); System.out.println(" filename: " + message.getFileName()); System.out.println(" line count: " + message.getLineCount()); System.out.println(" message number: " + message.getMessageNumber()); System.out.println(" subject: " + message.getSubject()); try { if (message.getAllRecipients() != null) for (Address address : message.getAllRecipients()) System.out.println(" address: " + address); } catch (final Exception ex) { System.out.println(ex.toString()); } } for (Message message : messages) { System.out.println("-----------------------------------------------------"); Object content; try { content = message.getContent(); if (javax.mail.Multipart.class.isInstance(content)) { System.out.println("CONTENT OBJECT CLASS: MULTIPART"); final javax.mail.Multipart multipart = (javax.mail.Multipart) content; System.out.println("multipart content type: " + multipart.getContentType()); System.out.println("multipart count: " + multipart.getCount()); for (int i = 0; i < multipart.getCount(); i++) { System.out.println(" multipart body[" + i + "]: " + multipart.getBodyPart(i)); BodyPart part = multipart.getBodyPart(i); System.out.println(" content-type: " + part.getContentType()); } } else if (String.class.isInstance(content)) { System.out.println("CONTENT IS A STRING: {" + content + "}"); } else { System.out.println("CONTENT OBJECT CLASS: " + content.getClass().toString()); } } catch (IOException e) { e.printStackTrace(); } } store.close(); }
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;//from w ww. j a va 2s. co m } 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:gov.nist.healthcare.ttt.parsing.Parsing.java
public static SOAPWithAttachment parseMtom(String mtom) throws MessagingException, IOException { // Parsing.fixMissingEndBoundry(mtom); MimeMultipart mp;/*www . j av a 2s . co m*/ // String contentType = Parsing.findContentType(mtom); // mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), ""), new ContentType(contentType)); mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), "multipart/related")); SOAPWithAttachment swa = new SOAPWithAttachment(); int count = mp.getCount(); for (int i = 0; i < count; i++) { BodyPart bp = mp.getBodyPart(i); String contentType = bp.getContentType(); if (contentType.startsWith("application/xop+xml")) { // SOAP ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent(); swa.setSoap(IOUtils.toString(content)); } else { Object contentRaw = bp.getContent(); if (contentRaw instanceof String) { String content = (String) bp.getContent(); swa.getAttachment().add(content.getBytes()); } else if (contentRaw instanceof SharedByteArrayInputStream) { SharedByteArrayInputStream content = (SharedByteArrayInputStream) bp.getContent(); swa.getAttachment().add(read(content)); } else { System.out.println("UNKNOWN ATTACHMENT TYPE = " + contentRaw.getClass().getName()); swa.getAttachment().add(new String().getBytes()); } } // System.out.println("contentype=" + bp.getContentType()); //ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent(); //String contentString = IOUtils.toString(content); //String contentString = (String) bp.getContent(); /* try { Envelope env = (Envelope) JAXB.unmarshal(new StringReader(contentString), Envelope.class); if (env.getHeader() == null && env.getBody() == null) { swa.getAttachment().add(Parsing.read(content)); //swa.getAttachment().add(contentString.getBytes()); } else { swa.setSoap(contentString); } } catch (Exception saxe) { // Not SOAP so must be attachment. swa.getAttachment().add(Parsing.read(content)); //swa.getAttachment().add(contentString.getBytes()); } */ } if (swa.getAttachment() == null || swa.getAttachment().size() == 0) { byte[] document = Parsing.getDocumentFromSoap(swa.getSoap()).getBytes(); Collection<byte[]> attachments = new ArrayList<byte[]>(); attachments.add(document); swa.setAttachment(attachments); } return swa; }
From source file:com.zotoh.crypto.MICUte.java
private static Object fromMP(Multipart mp) throws Exception { ContentType ct = new ContentType(mp.getContentType()); BodyPart bp; Object contents;//w w w .jav a 2 s . co m Object rc = null; int count = mp.getCount(); if ("multipart/mixed".equalsIgnoreCase(ct.getBaseType())) { if (count > 0) { bp = mp.getBodyPart(0); contents = bp.getContent(); // check for EDI payload sent as attachment String ctype = bp.getContentType(); boolean getNextPart = false; if (ctype.indexOf("text/plain") >= 0) { if (contents instanceof String) { String bodyText = "This is a generated cryptographic message in MIME format"; if (((String) contents).startsWith(bodyText)) { getNextPart = true; } } if (!getNextPart) { // check for a content disposition // if disposition type is attachment, then this is a doc getNextPart = true; String disp = bp.getDisposition(); if (disp != null && disp.toLowerCase().equals("attachment")) getNextPart = false; } } if ((count >= 2) && getNextPart) { bp = mp.getBodyPart(1); contents = bp.getContent(); } if (contents instanceof String) { rc = asBytes((String) contents); } else if (contents instanceof byte[]) { rc = contents; } else if (contents instanceof InputStream) { rc = contents; } else { String cn = contents == null ? "null" : contents.getClass().getName(); throw new Exception("Unsupport MIC object: " + cn); } } } else if (count > 0) { bp = mp.getBodyPart(0); contents = bp.getContent(); if (contents instanceof String) { rc = asBytes((String) contents); } else if (contents instanceof byte[]) { rc = contents; } else if (contents instanceof InputStream) { rc = contents; } else { String cn = contents == null ? "null" : contents.getClass().getName(); throw new Exception("Unsupport MIC object: " + cn); } } return rc; }
From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java
public static Body getMessageBody(MimeMessage message, String mimeType) { try {//from w w w . ja v a2 s. com 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:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java
public static List<Attachment> getMessageAttachments(MimeMessage message) { List<Attachment> attachments = new LinkedList<>(); try {//w ww . j a v a 2s .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: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// w ww . jav a 2 s.c o m * @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:org.alfresco.cacheserver.MultipartTest.java
private List<Patch> getPatches(String nodeId, long nodeVersion) throws MessagingException, IOException { List<Patch> patches = new LinkedList<>(); StringBuilder sb = new StringBuilder(); sb.append("/patch/"); sb.append(nodeId);//from w w w.ja v a2s .c o m sb.append("/"); sb.append(nodeVersion); String url = sb.toString(); final ClientConfig config = new DefaultClientConfig(); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); final Client client = Client.create(config); final WebResource resource = client.resource(url); final MimeMultipart response = resource.get(MimeMultipart.class); // This will iterate the individual parts of the multipart response for (int i = 0; i < response.getCount(); i++) { final BodyPart part = response.getBodyPart(i); System.out.printf("Embedded Body Part [Mime Type: %s, Length: %s]\n", part.getContentType(), part.getSize()); InputStream in = part.getInputStream(); // Patch patch = new Patch(); // patches.add(patch); } return patches; }
From source file:eu.openanalytics.rsb.EmailDepositITCase.java
private BodyPart getMailBodyPart(final Multipart parts, final String contentType) throws MessagingException { for (int i = 0; i < parts.getCount(); i++) { final BodyPart part = parts.getBodyPart(i); if (StringUtils.startsWith(part.getContentType(), contentType)) { return part; }//w w w . j a va2 s . c o m } throw new IllegalStateException("No part of type " + contentType + " found"); }
From source file:com.canoo.webtest.plugins.emailtest.EmailMessageContentFilter.java
private void extractMultiPartMessage(final Multipart parts, final int partIndex) throws MessagingException { try {/*from www.ja v a2 s .co m*/ if (partIndex >= parts.getCount()) { throw new StepFailedException("PartIndex too large.", this); } final BodyPart part = parts.getBodyPart(partIndex); final String contentType = part.getContentType(); if (!StringUtils.isEmpty(getContentType()) && !contentType.equals(getContentType())) { throw new MessagingException("Actual contentType of '" + contentType + "' did not match expected contentType of '" + fContentType + "'"); } final String disp = part.getDisposition(); final String filename = part.getFileName(); final InputStream inputStream = part.getInputStream(); if (Part.ATTACHMENT.equals(disp)) { fFilename = filename; } else { fFilename = getClass().getName(); } ContextHelper.defineAsCurrentResponse(getContext(), IOUtils.toString(inputStream), contentType, "http://" + fFilename); } catch (IOException e) { throw new MessagingException("Error extracting part: " + e.getMessage()); } }