List of usage examples for javax.mail BodyPart getContentType
public String getContentType() throws MessagingException;
From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java
public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent, final boolean withHtmlContent, final boolean preferHtmlContent, 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())); }/*from w ww . j a va2s . 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, preferHtmlContent); 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 (withHtmlContent) { // try { String htmlContent = getText(jmm, 0, true); im.setHtmlContent(htmlContent); // } 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; }
From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java
@Override public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception { if (askGmailPassword || gmailPassword == null || gmailUsername == null) { Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(), "Enter Gmail Credentials", getGmailUsername(), getGmailPassword()); if (credentials == null) return null; setGmailUsername(credentials.first()); setGmailPassword(credentials.second()); PluginUtils.saveProperties("conf/rockblock.props", this); askGmailPassword = false;/*from ww w.j a v a2s.c o m*/ } Properties props = new Properties(); props.put("mail.store.protocol", "imaps"); ArrayList<IridiumMessage> messages = new ArrayList<>(); try { Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword()); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); int numMsgs = inbox.getMessageCount(); for (int i = numMsgs; i > 0; i--) { Message m = inbox.getMessage(i); if (m.getReceivedDate().before(timeSince)) { break; } else { MimeMultipart mime = (MimeMultipart) m.getContent(); for (int j = 0; j < mime.getCount(); j++) { BodyPart p = mime.getBodyPart(j); Matcher matcher = pattern.matcher(p.getContentType()); if (matcher.matches()) { InputStream stream = (InputStream) p.getContent(); byte[] data = IOUtils.toByteArray(stream); IridiumMessage msg = process(data, matcher.group(1)); if (msg != null) messages.add(msg); } } } } } catch (NoSuchProviderException ex) { ex.printStackTrace(); System.exit(1); } catch (MessagingException ex) { ex.printStackTrace(); System.exit(2); } return messages; }
From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java
@Validated @Test//w w w.j a v a 2s . com public void testWriteToWithAttachment() throws Exception { SOAPMessage message = getFactory().createMessage(); message.getSOAPPart().getEnvelope().getBody().addBodyElement(new QName("urn:ns", "test", "p")); AttachmentPart attachment = message.createAttachmentPart(); attachment.setDataHandler(new DataHandler("This is a test", "text/plain; charset=iso-8859-15")); message.addAttachmentPart(attachment); ByteArrayOutputStream baos = new ByteArrayOutputStream(); message.writeTo(baos); System.out.write(baos.toByteArray()); MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), "multipart/related")); assertEquals(2, mp.getCount()); BodyPart part1 = mp.getBodyPart(0); // TODO // assertEquals(messageSet.getVersion().getContentType(), part1.getContentType()); BodyPart part2 = mp.getBodyPart(1); // Note: text/plain is the default content type, so we need to include the parameters in the assertion assertEquals("text/plain; charset=iso-8859-15", part2.getContentType()); }
From source file:MultipartViewer.java
protected void setupDisplay(Multipart mp) { // we display the first body part in a main frame on the left, and then // on the right we display the rest of the parts as attachments GridBagConstraints gc = new GridBagConstraints(); gc.gridheight = GridBagConstraints.REMAINDER; gc.fill = GridBagConstraints.BOTH; gc.weightx = 1.0;/*from w ww .j a v a2 s . com*/ gc.weighty = 1.0; // get the first part try { BodyPart bp = mp.getBodyPart(0); Component comp = getComponent(bp); add(comp, gc); } catch (MessagingException me) { add(new Label(me.toString()), gc); } // see if there are more than one parts try { int count = mp.getCount(); // setup how to display them gc.gridwidth = GridBagConstraints.REMAINDER; gc.gridheight = 1; gc.fill = GridBagConstraints.NONE; gc.anchor = GridBagConstraints.NORTH; gc.weightx = 0.0; gc.weighty = 0.0; gc.insets = new Insets(4, 4, 4, 4); // for each one we create a button with the content type for (int i = 1; i < count; i++) { // we skip the first one BodyPart curr = mp.getBodyPart(i); String label = null; if (label == null) label = curr.getFileName(); if (label == null) label = curr.getDescription(); if (label == null) label = curr.getContentType(); Button but = new Button(label); but.addActionListener(new AttachmentViewer(curr)); add(but, gc); } } catch (MessagingException me2) { me2.printStackTrace(); } }
From source file:com.consol.citrus.mail.message.MailMessageConverter.java
/** * Construct multipart body with first part being the body content and further parts being the attachments. * @param body// ww w . j av a 2 s .c o m * @return * @throws IOException */ private BodyPart handleMultiPart(Multipart body) throws IOException, MessagingException { BodyPart bodyPart = null; for (int i = 0; i < body.getCount(); i++) { MimePart entity = (MimePart) body.getBodyPart(i); if (bodyPart == null) { bodyPart = handlePart(entity); } else { BodyPart attachment = handlePart(entity); bodyPart.addPart(new AttachmentPart(attachment.getContent(), parseContentType(attachment.getContentType()), entity.getFileName())); } } return bodyPart; }
From source file:org.springintegration.demo.service.EmailTransformer.java
public void handleMultipart(Multipart multipart, javax.mail.Message mailMessage, List<Message<?>> messages) { final int count; try {//from w w w .j a v a 2 s . c om count = multipart.getCount(); } 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; final String filename; final String disposition; final String subject; try { contentType = bp.getContentType(); filename = bp.getFileName(); disposition = bp.getDisposition(); subject = mailMessage.getSubject(); } catch (MessagingException e) { throw new IllegalStateException("Unable to retrieve body part meta data.", e); } if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) { LOGGER.info("Handdling attachment '{}', type: '{}'", 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) { final Message<String> message = MessageBuilder.withPayload((String) content) .setHeader(FileHeaders.FILENAME, subject + ".txt").build(); messages.add(message); } else if (content instanceof InputStream) { InputStream inputStream = (InputStream) content; ByteArrayOutputStream bis = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, bis); } catch (IOException e) { throw new IllegalStateException( "Error while copying input stream to the ByteArrayOutputStream.", e); } Message<byte[]> message = MessageBuilder.withPayload((bis.toByteArray())) .setHeader(FileHeaders.FILENAME, filename).build(); messages.add(message); } else if (content instanceof javax.mail.Message) { handleMessage((javax.mail.Message) content, messages); } else if (content instanceof Multipart) { Multipart mp2 = (Multipart) content; handleMultipart(mp2, mailMessage, messages); } else { throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName()); } } }
From source file:com.glaf.mail.business.MailBean.java
/** * ??/*w w w. j av a 2 s.co m*/ * * @param part * @return * @throws MessagingException * @throws IOException */ public boolean isContainAttch(Part part) throws MessagingException, IOException { boolean flag = false; if (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart) part.getContent(); int count = multipart.getCount(); for (int i = 0; i < count; i++) { BodyPart bodypart = multipart.getBodyPart(i); String dispostion = bodypart.getDisposition(); if ((dispostion != null) && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) { flag = true; } else if (bodypart.isMimeType("multipart/*")) { flag = isContainAttch(bodypart); } else { String contentType = bodypart.getContentType(); if (contentType.toLowerCase().indexOf("appliaction") != -1) { flag = true; } if (contentType.toLowerCase().indexOf("name") != -1) { flag = true; } } } } else if (part.isMimeType("message/rfc822")) { flag = isContainAttch((Part) part.getContent()); } return flag; }
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
private EmailMessageContent getMessageContent(Object content, String mimeType) throws IOException, MessagingException { // if this content item is a String, simply return it. if (content instanceof String) { return new EmailMessageContent((String) content, isHtml(mimeType)); }//from w w w . j a va 2 s . c o m else if (content instanceof MimeMultipart) { Multipart m = (Multipart) content; int parts = m.getCount(); // iterate backwards through the parts list for (int i = parts - 1; i >= 0; i--) { EmailMessageContent result = null; BodyPart part = m.getBodyPart(i); Object partContent = part.getContent(); String contentType = part.getContentType(); boolean isHtml = isHtml(contentType); log.debug("Examining Multipart " + i + " with type " + contentType + " and class " + partContent.getClass()); if (partContent instanceof String) { result = new EmailMessageContent((String) partContent, isHtml); } else if (partContent instanceof InputStream && (contentType.startsWith("text/html"))) { StringWriter writer = new StringWriter(); IOUtils.copy((InputStream) partContent, writer); result = new EmailMessageContent(writer.toString(), isHtml); } else if (partContent instanceof MimeMultipart) { result = getMessageContent(partContent, contentType); } if (result != null) { return result; } } } return null; }
From source file:immf.SendMailBridge.java
private void parseBodypart(SenderMail sendMail, BodyPart bp, String subtype, String parentSubtype) throws IOException { boolean limiterr = false; String badfile = null;// www. j a v a 2 s . co m try { String contentType = bp.getContentType().toLowerCase(); log.info("Bodypart ContentType:" + contentType); log.info("subtype:" + subtype); if (contentType.startsWith("multipart/")) { parseMultipart(sendMail, (Multipart) bp.getContent(), getSubtype(contentType), subtype); } else if (sendMail.getPlainTextContent() == null && contentType.startsWith("text/plain")) { // ???plain/text? String content = (String) bp.getContent(); log.info("set Content text [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); sendMail.setPlainTextContent(content); } else if (sendMail.getHtmlContent() == null && contentType.startsWith("text/html") && (subtype.equalsIgnoreCase("alternative") || subtype.equalsIgnoreCase("related"))) { String content = (String) bp.getContent(); log.info("set Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); // html???? sendMail.setHtmlContent(content); } else if (contentType.startsWith("text/html")) { // subtype?mixed?? String content = (String) bp.getContent(); if (sendMail.getHtmlContent() == null) { // text/plain???????? text/html????????? log.info("set Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); // html???? sendMail.setHtmlContent(content); } else { log.info("Discarding duplicate content [" + content + "]"); } } else { log.debug("attach"); // ???? if (subtype.equalsIgnoreCase("related")) { // SenderAttachment file = new SenderAttachment(); String fname = uniqId(); String fname2 = Util.getFileName(bp); // iPhone?gifpng?????????????ContentType(?png???gif?) if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); fname = fname + ".gif"; fname2 = getBasename(fname2) + ".gif"; file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setContentType(contentType); fname = fname + "." + getSubtype(contentType); file.setData(inputstream2bytes(bp.getInputStream())); } file.setInline(true); boolean inline = !this.forcePlainText & sendMail.checkAttachmentCapability(file); if (!inline) { file.setInline(false); if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = fname2; throw new Exception("Attachments: size limit or file count limit exceeds!"); } } if (inline) { file.setFilename(fname); file.setContentId(bp.getHeader("Content-Id")[0]); log.info("Inline Attachment " + file.loggingString() + ", Hash:" + file.getHash()); } else { file.setFilename(fname2); log.info("Attachment " + file.loggingString()); } sendMail.addAttachmentFileIdList(file); } else { // ? SenderAttachment file = new SenderAttachment(); file.setInline(false); file.setContentType(contentType); String fname = Util.getFileName(bp); if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); file.setFilename(getBasename(fname) + ".gif"); file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setFilename(fname); file.setData(inputstream2bytes(bp.getInputStream())); } if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = file.getFilename(); throw new Exception("Attachments: size limit or file count limit exceeds!"); } sendMail.addAttachmentFileIdList(file); log.info("Attachment " + file.loggingString()); } } } catch (Exception e) { log.error("parse bodypart error.", e); if (limiterr) { sendMail.addPlainTextContent("\n[(" + badfile + ")]"); if (sendMail.getHtmlContent() != null) { sendMail.addHtmlContent("[(" + badfile + ")]<br>"); } } else { throw new IOException("BodyPart error." + e.getMessage(), e); } } }
From source file:immf.SendMailBridge.java
private void parseBodypartmixed(SenderMail sendMail, BodyPart bp, String subtype, String parentSubtype) throws IOException { boolean limiterr = false; String badfile = null;/* www .j av a2s. c om*/ try { String contentType = bp.getContentType().toLowerCase(); log.info("Bodypart ContentType:" + contentType); log.info("subtype:" + subtype); if (contentType.startsWith("multipart/")) { parseMultipart(sendMail, (Multipart) bp.getContent(), getSubtype(contentType), subtype); } else if (sendMail.getPlainTextContent() == null && contentType.startsWith("text/plain")) { // ???plain/text? String content = (String) bp.getContent(); log.info("set Content text [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); sendMail.setPlainTextContent(content); // HTML??????<br>????????HtmlConverter? // ??????HTML???HTML??????? if (sendMail.getHtmlWorkingContent() == null) { sendMail.setHtmlWorkingContent( "<body>" + Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>"); } else { sendMail.addHtmlWorkingContent( Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>"); } } else if (sendMail.getHtmlContent() == null && contentType.startsWith("text/html") && (parentSubtype.equalsIgnoreCase("alternative") || parentSubtype.equalsIgnoreCase("related"))) { // ???text/html String content = (String) bp.getContent(); log.info("set Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); // 2?3?HTML?????????</body>??????? content = this.charConv.convert(content, charset); content = HtmlConvert.replaceAllCaseInsenstive(content, "</body>.*", ""); log.debug(" conv " + content); sendMail.setHtmlContent(content); } else { log.debug("attach"); // ???? String contentDisposition = bp.getDisposition(); if (contentDisposition != null && contentDisposition.equalsIgnoreCase(Part.INLINE)) { // SenderAttachment file = new SenderAttachment(); String uniqId = uniqId(); String fname = uniqId; String fname2 = Util.getFileName(bp); // iPhone?gifpng?????????????gif??(?png???gif?) if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); fname = fname + ".gif"; fname2 = getBasename(fname2) + ".gif"; file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setContentType(contentType); fname = fname + "." + getSubtype(contentType); file.setData(inputstream2bytes(bp.getInputStream())); } file.setInline(true); boolean inline = !this.forcePlainText & sendMail.checkAttachmentCapability(file); if (!inline) { file.setInline(false); if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = fname2; throw new Exception("Attachments: size limit or file count limit exceeds!"); } } if (inline) { file.setFilename(fname); if (bp.getHeader("Content-Id") == null) { file.setContentId(uniqId); } else { file.setContentId(bp.getHeader("Content-Id")[0]); } log.info("Inline Attachment(mixed) " + file.loggingString() + ", Hash:" + file.getHash()); // ??HTML? if (sendMail.getHtmlContent() != null) { sendMail.addHtmlContent("<img src=\"cid:" + file.getContentId() + "\"><br>"); } if (sendMail.getHtmlWorkingContent() == null) { sendMail.setHtmlWorkingContent( "<body><img src=\"cid:" + file.getContentId() + "\"><br>"); } else { sendMail.addHtmlWorkingContent("<img src=\"cid:" + file.getContentId() + "\"><br>"); } } else { file.setFilename(fname2); log.info("Attachment " + file.loggingString()); } sendMail.addAttachmentFileIdList(file); } else { // ? SenderAttachment file = new SenderAttachment(); file.setInline(false); file.setContentType(contentType); String fname = Util.getFileName(bp); if (fname == null && sendMail.getPlainTextContent() != null && contentType.startsWith("text/plain")) { // ??????? String content = (String) bp.getContent(); log.info("add Content text [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); // ??HTML????<br> sendMail.addPlainTextContent("\n" + content); sendMail.addHtmlWorkingContent( Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>"); } else if (fname == null && sendMail.getHtmlContent() != null && contentType.startsWith("text/html") && (parentSubtype.equalsIgnoreCase("alternative") || parentSubtype.equalsIgnoreCase("related"))) { // ????text/html???? String content = (String) bp.getContent(); log.info("add Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); content = HtmlConvert.replaceAllCaseInsenstive(content, ".*<body[^>]*>", ""); content = HtmlConvert.replaceAllCaseInsenstive(content, "</body>.*", ""); log.debug(" conv " + content); sendMail.addHtmlContent(content); } else { // ?????? if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); file.setFilename(getBasename(fname) + ".gif"); file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setFilename(fname); file.setData(inputstream2bytes(bp.getInputStream())); } if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = file.getFilename(); throw new Exception("Attachments: size limit or file count limit exceeds!"); } sendMail.addAttachmentFileIdList(file); log.info("Attachment " + file.loggingString()); } } } } catch (Exception e) { log.error("parse bodypart error(mixed).", e); if (limiterr) { sendMail.addPlainTextContent("\n[(" + badfile + ")]"); if (sendMail.getHtmlContent() != null) { sendMail.addHtmlContent("[(" + badfile + ")]<br>"); } if (sendMail.getHtmlWorkingContent() == null) { sendMail.setHtmlWorkingContent("<body>[(" + badfile + ")]<br>"); } else { sendMail.addHtmlWorkingContent("[(" + badfile + ")]<br>"); } } else { throw new IOException("BodyPart error(mixed)." + e.getMessage(), e); } } }