List of usage examples for javax.mail BodyPart getContent
public Object getContent() throws IOException, MessagingException;
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 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); // 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); } } }
From source file:eu.peppol.as2.MdnMimeMessageInspector.java
public Map<String, String> getMdnFields() { Map<String, String> ret = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); try {/*from ww w. java 2s .c om*/ BodyPart bp = getMessageDispositionNotificationPart(); boolean contentIsBase64Encoded = false; // // look for base64 transfer encoded MDN's (when Content-Transfer-Encoding is present) // // Content-Type: message/disposition-notification // Content-Transfer-Encoding: base64 // // "Content-Transfer-Encoding not used in HTTP transport Because HTTP, unlike SMTP, // does not have an early history involving 7-bit restriction. // There is no need to use the Content Transfer Encodings of MIME." // String[] contentTransferEncodings = bp.getHeader("Content-Transfer-Encoding"); if (contentTransferEncodings != null && contentTransferEncodings.length > 0) { if (contentTransferEncodings.length > 1) log.warn("MDN has multiple Content-Transfer-Encoding, we only try the first one"); String encoding = contentTransferEncodings[0]; if (encoding == null) encoding = ""; encoding = encoding.trim(); log.info("MDN specifies Content-Transfer-Encoding : '" + encoding + "'"); if ("base64".equalsIgnoreCase(encoding)) { contentIsBase64Encoded = true; } } Object content = bp.getContent(); if (content instanceof InputStream) { InputStream contentInputStream = (InputStream) content; if (contentIsBase64Encoded) { log.debug("MDN seems to be base64 encoded, wrapping content stream in Base64 decoding stream"); contentInputStream = new Base64InputStream(contentInputStream); // wrap in base64 decoding stream } BufferedReader r = new BufferedReader(new InputStreamReader(contentInputStream)); while (r.ready()) { String line = r.readLine(); int firstColon = line.indexOf(":"); // "Disposition: ......" if (firstColon > 0) { String key = line.substring(0, firstColon).trim(); // up to : String value = line.substring(firstColon + 1).trim(); // skip : ret.put(key, value); } } } else { throw new Exception("Unsupported MDN content, expected InputStream found @ " + content.toString()); } } catch (Exception e) { throw new IllegalStateException("Unable to retrieve the values from the MDN : " + e.getMessage(), e); } return ret; }
From source file:mitm.application.djigzo.james.mailets.PDFEncryptTest.java
@Test public void testEncryptPDFFromPersonalUTF8() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); PDFEncrypt mailet = new PDFEncrypt(); mailetConfig.setInitParameter("template", "encrypted-pdf.ftl"); mailetConfig.setInitParameter("encryptedProcessor", "encryptedProcessor"); mailetConfig.setInitParameter("notEncryptedProcessor", "notEncryptedProcessor"); mailetConfig.setInitParameter("passwordMode", "single"); mailetConfig.setInitParameter("passThrough", "false"); mailet.init(mailetConfig);//from w ww . j a va2s .co m MockMail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/normal-message-with-attach.eml")); message.setFrom(new InternetAddress("test@example.com", "=?UTF-8?B?w6TDtsO8IMOEw5bDnA==?=")); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("m.brinkers@pobox.com")); recipients.add(new MailAddress("123@example.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("sender@example.com")); // password is test when encrypted with password 'djigzo' new DjigzoMailAttributesImpl(mail).setEncryptedPassword(Base64.decodeBase64(MiscStringUtils .toAsciiBytes("lklfx6SWxIkAAAAQ1VTbMJjznNZjVvdggckSPQAACAAAAAAQKAxcw630UmyVhyZPiW9xhg=="))); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); TestUtils.saveMessages(tempDir, "testEncryptPDFFromPersonalUTF8", listener.getMessages()); assertEquals(1, listener.getMessages().size()); assertEquals("encryptedProcessor", listener.getStates().get(0)); assertEquals(2, listener.getRecipients().get(0).size()); assertTrue(listener.getRecipients().get(0).contains(new MailAddress("123@example.com"))); assertTrue(listener.getRecipients().get(0).contains(new MailAddress("m.brinkers@pobox.com"))); assertEquals("sender@example.com", listener.getSenders().get(0).toString()); assertEquals(Mail.GHOST, mail.getState()); assertNotNull(listener.getMessages().get(0)); assertTrue(message != listener.getMessages().get(0)); MimeMessage encrypted = listener.getMessages().get(0); assertTrue(encrypted.isMimeType("multipart/mixed")); Multipart mp = (Multipart) encrypted.getContent(); assertEquals(2, mp.getCount()); BodyPart messagePart = mp.getBodyPart(0); BodyPart pdfPart = mp.getBodyPart(1); assertTrue(messagePart.isMimeType("text/plain")); assertTrue(pdfPart.isMimeType("application/pdf")); // check if the body contains (which is the decoded from personal name) String text = (String) messagePart.getContent(); assertTrue(text.contains(" ")); MailUtils.validateMessage(listener.getMessages().get(0)); }
From source file:mitm.application.djigzo.james.mailets.PDFEncryptTest.java
private void checkEncryption(MimeMessage message, String password, boolean hasReplyLink) throws Exception { /*/*from www . j a v a 2 s. c o m*/ * The message should be a mime multipart mixed with two parts. The first part should be readable text * and the second part should be the encrypted PDF */ assertTrue(message.isMimeType("multipart/mixed")); Multipart mp = (Multipart) message.getContent(); assertEquals(2, mp.getCount()); BodyPart textPart = mp.getBodyPart(0); assertTrue(textPart.isMimeType("text/plain")); BodyPart pdfPart = mp.getBodyPart(1); assertTrue(pdfPart.isMimeType("application/pdf")); PdfReader reader = new PdfReader(pdfPart.getInputStream(), password.getBytes(CharacterEncoding.US_ASCII)); String firstPageContent = new String(reader.getPageContent(1), CharacterEncoding.US_ASCII); /* * We just check whether the raw content contains (Reply) or not. */ if (hasReplyLink) { assertTrue(firstPageContent.contains("(Reply)")); assertTrue(((String) textPart.getContent()).contains("reply URL: http://127.0.0.1?env=")); } else { assertFalse(firstPageContent.contains("(Reply)")); } }
From source file:org.alfresco.email.server.impl.subetha.SubethaEmailMessage.java
private void parseMessagePart(Part messagePart) { try {// ww w . j a v a2 s.c om if (messagePart.isMimeType(MIME_PLAIN_TEXT) || messagePart.isMimeType(MIME_HTML_TEXT)) { if (log.isDebugEnabled()) { log.debug("Text or HTML part was found. ContentType: " + messagePart.getContentType()); } addBody(messagePart); } else if (messagePart.isMimeType(MIME_XML_TEXT)) { if (log.isDebugEnabled()) { log.debug("XML part was found."); } addAttachment(messagePart); } else if (messagePart.isMimeType(MIME_APPLICATION)) { if (log.isDebugEnabled()) { log.debug("Application part was found."); } addAttachment(messagePart); } else if (messagePart.isMimeType(MIME_IMAGE)) { if (log.isDebugEnabled()) { log.debug("Image part was found."); } addAttachment(messagePart); } else if (messagePart.isMimeType(MIME_MULTIPART)) { // if multipart, this method will be called recursively // for each of its parts Multipart mp = (Multipart) messagePart.getContent(); int count = mp.getCount(); if (log.isDebugEnabled()) { log.debug("MULTIPART with " + count + " part(s) found. Processin each part..."); } for (int i = 0; i < count; i++) { BodyPart bp = mp.getBodyPart(i); if (bp.getContent() instanceof MimeMultipart) { // It's multipart. Recurse. parseMessagePart(bp); } else { // It's the body addBody(bp); } } if (log.isDebugEnabled()) { log.debug("MULTIPART processed."); } } else if (messagePart.isMimeType(MIME_RFC822)) { // if rfc822, call this method with its content as the part if (log.isDebugEnabled()) { log.debug("MIME_RFC822 part found. Processing inside part..."); } parseMessagePart((Part) messagePart.getContent()); if (log.isDebugEnabled()) { log.debug("MIME_RFC822 processed."); } } else { // if all else fails, put this in the attachments map. // Actually we don't know what it is. if (log.isDebugEnabled()) { log.debug("Unrecognized part was found. Put it into attachments."); } addAttachment(messagePart); } } catch (IOException e) { throw new EmailMessageException(ERR_PARSE_MESSAGE, e.getMessage()); } catch (MessagingException e) { throw new EmailMessageException(ERR_PARSE_MESSAGE, e.getMessage()); } }
From source file:org.alfresco.repo.imap.RemoteLoadTester.java
public void testMailbox() { logger.info("Getting folder..."); long t = System.currentTimeMillis(); // Create empty properties Properties props = new Properties(); props.setProperty("mail.imap.partialfetch", "false"); // Get session Session session = Session.getDefaultInstance(props, null); Store store = null;//from w w w.java2 s . c o m Folder folder = null; try { // Get the store store = session.getStore("imap"); store.connect(REMOTE_HOST, USER_NAME, USER_PASSWORD); // Get folder folder = store.getFolder(TEST_FOLDER_NAME); folder.open(Folder.READ_ONLY); // Get directory Message message[] = folder.getMessages(); for (int i = 0, n = message.length; i < n; i++) { message[i].getAllHeaders(); Address[] from = message[i].getFrom(); System.out.print(i + ": "); if (from != null) { System.out.print(message[i].getFrom()[0] + "\t"); } System.out.println(message[i].getSubject()); Object content = message[i].getContent(); if (content instanceof MimeMultipart) { for (int j = 0, m = ((MimeMultipart) content).getCount(); j < m; j++) { BodyPart part = ((MimeMultipart) content).getBodyPart(j); Object partContent = part.getContent(); if (partContent instanceof String) { String body = (String) partContent; } else if (partContent instanceof FilterInputStream) { FilterInputStream fis = (FilterInputStream) partContent; BufferedInputStream bis = new BufferedInputStream(fis); /* while (bis.available() > 0) { bis.read(); }*/ byte[] bytes = new byte[524288]; while (bis.read(bytes) != -1) { } bis.close(); fis.close(); } } } int nn = 0; } t = System.currentTimeMillis() - t; logger.info("Time: " + t + " ms (" + t / 1000 + " s)"); logger.info("Length: " + message.length); } catch (Exception e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } finally { // Close connection try { if (folder != null) { folder.close(false); } } catch (MessagingException e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } try { if (store != null) { store.close(); } } catch (MessagingException e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } } }
From source file:org.apache.hupa.server.utils.MessageUtils.java
/** * Extract the attachments present in a mime message * * @param logger/* ww w . ja v a 2 s . c o m*/ * @param content * @return A list of body parts of the attachments * @throws MessagingException * @throws IOException */ static public List<BodyPart> extractMessageAttachments(Log logger, Object content) throws MessagingException, IOException { ArrayList<BodyPart> ret = new ArrayList<BodyPart>(); if (content instanceof Multipart) { Multipart part = (Multipart) content; for (int i = 0; i < part.getCount(); i++) { BodyPart bodyPart = part.getBodyPart(i); String fileName = bodyPart.getFileName(); String[] contentId = bodyPart.getHeader("Content-ID"); if (bodyPart.isMimeType("multipart/*")) { ret.addAll(extractMessageAttachments(logger, bodyPart.getContent())); } else { if (contentId != null || fileName != null) { ret.add(bodyPart); } } } } else { logger.error("Unknown content: " + content.getClass().getName()); } return ret; }
From source file:org.apache.james.postage.mail.MailMatchingUtils.java
public static int getMimePartSize(MimeMultipart parts, String mimeType) { if (parts != null) { try {/*from w w w . ja va2 s. c om*/ for (int i = 0; i < parts.getCount(); i++) { BodyPart bodyPart = parts.getBodyPart(i); if (bodyPart.getContentType().startsWith(mimeType)) { try { Object content = bodyPart.getContent(); if (content instanceof InputStream) { ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(((InputStream) content), os); return os.size(); } else if (content instanceof String) { return ((String) content).length(); } else { throw new IllegalStateException( "Unsupported content: " + content.getClass().toString()); } } catch (IOException e) { throw new IllegalStateException("Unexpected IOException in getContent()"); } } } } catch (MessagingException e) { log.info("failed to process body parts.", e); } } return 0; }
From source file:org.apache.james.transport.mailets.DSNBounceTest.java
@Test public void serviceShouldSendMultipartMailContainingTextPart() throws Exception { FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME) .mailetContext(fakeMailContext).build(); dsnBounce.init(mailetConfig);//from w w w. j ava 2s.c o m MailAddress senderMailAddress = new MailAddress("sender@domain.com"); FakeMail mail = FakeMail.builder().sender(senderMailAddress).attribute("delivery-error", "Delivery error") .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")).name(MAILET_NAME) .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z"))) .build(); dsnBounce.service(mail); String hostname = InetAddress.getLocalHost().getHostName(); String expectedContent = "Hi. This is the James mail server at " + hostname + ".\nI'm afraid I wasn't able to deliver your message to the following addresses.\nThis is a permanent error; I've given up. Sorry it didn't work out. Below\nI include the list of recipients and the reason why I was unable to deliver\nyour message.\n\n" + "Failed recipient(s):\n" + "recipient@domain.com\n" + "\n" + "Error message:\n" + "Delivery error\n" + "\n"; List<SentMail> sentMails = fakeMailContext.getSentMails(); assertThat(sentMails).hasSize(1); SentMail sentMail = sentMails.get(0); MimeMessage sentMessage = sentMail.getMsg(); MimeMultipart content = (MimeMultipart) sentMessage.getContent(); BodyPart bodyPart = content.getBodyPart(0); assertThat(bodyPart.getContentType()).isEqualTo("text/plain; charset=us-ascii"); assertThat(bodyPart.getContent()).isEqualTo(expectedContent); }
From source file:org.apache.james.transport.mailets.DSNBounceTest.java
@Test public void serviceShouldSendMultipartMailContainingTextPartWhenCustomMessageIsConfigured() throws Exception { FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME) .mailetContext(fakeMailContext).setProperty("messageString", "My custom message\n").build(); dsnBounce.init(mailetConfig);//from w ww.j a va2 s. com MailAddress senderMailAddress = new MailAddress("sender@domain.com"); FakeMail mail = FakeMail.builder().sender(senderMailAddress).attribute("delivery-error", "Delivery error") .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")).name(MAILET_NAME) .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z"))) .build(); dsnBounce.service(mail); String expectedContent = "My custom message\n\n" + "Failed recipient(s):\n" + "recipient@domain.com\n" + "\n" + "Error message:\n" + "Delivery error\n" + "\n"; List<SentMail> sentMails = fakeMailContext.getSentMails(); assertThat(sentMails).hasSize(1); SentMail sentMail = sentMails.get(0); MimeMessage sentMessage = sentMail.getMsg(); MimeMultipart content = (MimeMultipart) sentMessage.getContent(); BodyPart bodyPart = content.getBodyPart(0); assertThat(bodyPart.getContentType()).isEqualTo("text/plain; charset=us-ascii"); assertThat(bodyPart.getContent()).isEqualTo(expectedContent); }