List of usage examples for javax.mail BodyPart getDisposition
public String getDisposition() throws MessagingException;
From source file:com.glaf.mail.business.MailBean.java
/** * ?/*from w w w . j a v a 2 s.c o m*/ * * @param part * @throws MessagingException * @throws IOException */ public void parseAttachment(Part part) throws MessagingException, IOException { String filename = ""; if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mpart = mp.getBodyPart(i); String dispostion = mpart.getDisposition(); if ((dispostion != null) && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) { filename = mpart.getFileName(); if (filename != null) { logger.debug("orig filename=" + filename); if (filename.indexOf("?") != -1) { filename = new String(filename.getBytes("GBK"), "UTF-8"); } if (filename.toLowerCase().indexOf("gb2312") != -1) { filename = MimeUtility.decodeText(filename); } filename = MailUtils.convertString(filename); logger.debug("filename=" + filename); parseFileContent(filename, mpart.getInputStream()); } } else if (mpart.isMimeType("multipart/*")) { parseAttachment(mpart); } else { filename = mpart.getFileName(); if (filename != null) { logger.debug("orig filename=" + filename); if (filename.indexOf("?") != -1) { filename = new String(filename.getBytes("GBK"), "UTF-8"); } if (filename.toLowerCase().indexOf("gb2312") != -1) { filename = MimeUtility.decodeText(filename); } filename = MailUtils.convertString(filename); parseFileContent(filename, mpart.getInputStream()); logger.debug("filename=" + filename); } } } } else if (part.isMimeType("message/rfc822")) { parseAttachment((Part) part.getContent()); } }
From source file:com.canoo.webtest.plugins.emailtest.EmailMessageContentFilter.java
private void extractMultiPartMessage(final Multipart parts, final int partIndex) throws MessagingException { try {/*from w w w . j ava2s . c om*/ 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()); } }
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 ww . j a v a2 s. com 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:fr.gouv.culture.vitam.eml.EmlExtract.java
private static final String addSubIdentities(Element identification, BodyPart bp, InputStream inputStream, VitamArgument argument, ConfigLoader config) { Element newElt = XmlDom.factory.createElement(EMAIL_FIELDS.subidentity.name); String filename = null;/* www . j av a 2 s . c o m*/ String result = ""; try { filename = bp.getFileName(); filename = StringUtils.toFileName(filename); if (filename != null) { Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.filename.name); elt.setText(filename); newElt.add(elt); } else { filename = "eml.eml"; } } catch (MessagingException e) { } try { int size = bp.getSize(); if (size > 0) { Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.attSize.name); elt.setText(Integer.toString(size)); newElt.add(elt); } } catch (MessagingException e) { } try { String description = bp.getDescription(); if (description != null) { Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.description.name); elt.setText(description); newElt.add(elt); } } catch (MessagingException e) { } try { String disposition = bp.getDisposition(); if (disposition != null) { Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.disposition.name); elt.setText(disposition); newElt.add(elt); } } catch (MessagingException e) { } File filetemp = null; FileOutputStream outputStream = null; try { // Force out to analysis if (config.extractFile) { filetemp = new File(argument.currentOutputDir, filename); } else { filetemp = File.createTempFile(StaticValues.PREFIX_TEMPFILE, filename); } byte[] buffer = new byte[8192]; int read = 0; outputStream = new FileOutputStream(filetemp); while ((read = inputStream.read(buffer)) >= 0) { outputStream.write(buffer, 0, read); } outputStream.close(); outputStream = null; } catch (IOException e1) { if (filetemp != null && !config.extractFile) { filetemp.delete(); } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { } } String status = "Error during access to attachment"; newElt.addAttribute(EMAIL_FIELDS.status.name, status); identification.add(newElt); return ""; } try { Commands.addFormatIdentification(newElt, filename, filetemp, config, argument); if (argument.extractKeyword) { // get back keyword in the main list Element keyw = (Element) newElt.selectSingleNode(EMAIL_FIELDS.keywords.name); if (keyw != null) { StringBuilder builder = new StringBuilder(); @SuppressWarnings("unchecked") List<Element> elts = (List<Element>) keyw.selectNodes(EMAIL_FIELDS.keywordRank.name); for (Element elt : elts) { String value = elt.attributeValue(EMAIL_FIELDS.keywordOccur.name); int occur = Integer.parseInt(value) / 2 + 1; @SuppressWarnings("unchecked") List<Element> words = (List<Element>) elt.selectNodes(EMAIL_FIELDS.keywordWord.name); for (Element eword : words) { String word = eword.attributeValue(EMAIL_FIELDS.keywordValue.name) + " "; for (int i = 0; i < occur; i++) { builder.append(word); } } } result = builder.toString().trim(); } } } catch (Exception e) { String status = "Error during identification"; e.printStackTrace(); config.addRankId(newElt); newElt.addAttribute(EMAIL_FIELDS.status.name, status); } if (filetemp != null && !config.extractFile) { filetemp.delete(); } identification.add(newElt); return result; }
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;//from ww w .jav a2s . c o 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); // 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); } } }