List of usage examples for javax.mail BodyPart getContent
public Object getContent() throws IOException, MessagingException;
From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java
/** * Gets plain text version of the content. Has some limitations - won't * handle nested attachments well.//from ww w . ja v a 2s. co m * * @return String representation of the message */ @Override public String getContentText() { try { Object content = source.getContent(); StringBuilder result = new StringBuilder(); if (content instanceof String) { result.append(content); } else if (content instanceof Multipart) { Multipart parts = (Multipart) content; for (int i = 0; i < parts.getCount(); i++) { BodyPart part = parts.getBodyPart(i); if (part.getContent() instanceof String) { result.append(part.getContent()); } } } return result.toString(); } catch (Exception e) { throw new GmailException( "Failed getting text content from " + "JavaMailGmailMessage. You could try handling " + "((JavaMailGmailMessage).getMessage()) manually", e); } }
From source file:mitm.application.djigzo.ca.PFXMailBuilderTest.java
private byte[] getPFX(MimeMessage message) throws Exception { Multipart mp;//from w w w .jav a 2s . c o m mp = (Multipart) message.getContent(); BodyPart pdfPart = null; for (int i = 0; i < mp.getCount(); i++) { BodyPart part = mp.getBodyPart(i); if (part.isMimeType("application/octet-stream")) { pdfPart = part; } } assertNotNull(pdfPart); Object content = pdfPart.getContent(); assertTrue(content instanceof ByteArrayInputStream); return IOUtils.toByteArray((ByteArrayInputStream) content); }
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;/* w w w . ja v a 2 s . co 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:net.fenyo.mail4hotspot.service.MailManager.java
private String getMultipartContentString(final MimeMultipart multipart, final boolean mixed) throws IOException, MessagingException { // content-type: multipart/mixed ou multipart/alternative final StringBuffer selected_content = new StringBuffer(); for (int i = 0; i < multipart.getCount(); i++) { final BodyPart body_part = multipart.getBodyPart(i); final Object content = body_part.getContent(); final String content_string; if (String.class.isInstance(content)) if (body_part.isMimeType("text/html")) content_string = GenericTools.html2Text((String) content); else if (body_part.isMimeType("text/plain")) content_string = (String) content; else { log.warn("body part content-type not handled: " + body_part.getContentType() + " -> downgrading to String"); content_string = (String) content; }/* w w w.j a va 2 s . c o m*/ else if (MimeMultipart.class.isInstance(content)) { boolean part_mixed = false; if (body_part.isMimeType("multipart/mixed")) part_mixed = true; else if (body_part.isMimeType("multipart/alternative")) part_mixed = false; else { log.warn("body part content-type not handled: " + body_part.getContentType() + " -> downgrading to multipart/mixed"); part_mixed = true; } content_string = getMultipartContentString((MimeMultipart) content, part_mixed); } else { log.warn("invalid body part content type and class: " + content.getClass().toString() + " - " + body_part.getContentType()); content_string = ""; } if (mixed == false) { // on slectionne la premire part non vide - ce n'est pas forcment la meilleure alternative, mais comment diffrentiel un text/plain d'une pice jointe d'un text/plain du corps du message, accompagnant un text/html du mme corps ??? if (selected_content.length() == 0) selected_content.append(content_string); } else { if (selected_content.length() > 0 && content_string.length() > 0) selected_content.append("\r\n---\r\n"); selected_content.append(content_string); } } return selected_content.toString(); }
From source file:com.seleniumtests.connectors.mails.ImapClient.java
/** * get list of all emails in folder//from ww w. ja v a2s .c o m * * @param folderName folder to read * @param firstMessageTime date from which we should get messages * @param firstMessageIndex index of the firste message to find * @throws MessagingException * @throws IOException */ @Override public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime) throws MessagingException, IOException { if (folderName == null) { throw new MessagingException("folder ne doit pas tre vide"); } // Get folder Folder folder = store.getFolder(folderName); folder.open(Folder.READ_ONLY); // Get directory Message[] messages = folder.getMessages(); List<Message> preFilteredMessages = new ArrayList<>(); final LocalDateTime firstTime = firstMessageTime; // on filtre les message en fonction du mode de recherche if (searchMode == SearchMode.BY_INDEX || firstTime == null) { for (int i = firstMessageIndex, n = messages.length; i < n; i++) { preFilteredMessages.add(messages[i]); } } else { preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() { private static final long serialVersionUID = 1L; @Override public boolean match(Message msg) { try { return !msg.getReceivedDate() .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant())); } catch (MessagingException e) { return false; } } })); } List<Email> filteredEmails = new ArrayList<>(); lastMessageIndex = messages.length; for (Message message : preFilteredMessages) { String contentType = ""; try { contentType = message.getContentType(); } catch (MessagingException e) { MimeMessage msg = (MimeMessage) message; message = new MimeMessage(msg); contentType = message.getContentType(); } // decode content String messageContent = ""; List<String> attachments = new ArrayList<>(); if (contentType.toLowerCase().contains("text/html")) { messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString()); } else if (contentType.toLowerCase().contains("multipart/")) { List<BodyPart> partList = getMessageParts((Multipart) message.getContent()); // store content in list for (BodyPart part : partList) { String partContentType = part.getContentType().toLowerCase(); if (partContentType.contains("text/html")) { messageContent = messageContent .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString())); } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) { messageContent = messageContent.concat((String) part.getContent().toString()); } else if (partContentType.contains("image") || partContentType.contains("application/") || partContentType.contains("text/x-vcard")) { if (part.getFileName() != null) { attachments.add(part.getFileName()); } else { attachments.add(part.getDescription()); } } else { logger.debug("type: " + part.getContentType()); } } } // create a new email filteredEmails.add(new Email(message.getSubject(), messageContent, "", message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), attachments)); } folder.close(false); return filteredEmails; }
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 ww w. ja va 2s . co 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.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 www. j ava 2s. 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:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
@Test public void testMultipartWithIllegalContentTransferEncoding() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); mailetConfig.setInitParameter("algorithm", "AES128"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailet.init(mailetConfig);/*from w ww. j a v a 2 s.co m*/ Mail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/quoted-printable-multipart.eml")); assertTrue(message.isMimeType("multipart/mixed")); MimeMultipart mp = (MimeMultipart) message.getContent(); assertEquals(2, mp.getCount()); BodyPart part = mp.getBodyPart(0); assertTrue(part.isMimeType("text/plain")); assertEquals("==", (String) part.getContent()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); mailAttributes.setCertificates(certificates); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider( loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test"); SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), keyStore, "BC"); assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType()); assertEquals(SMIMEEncryptionAlgorithm.AES128_CBC.getOID().toString(), inspector.getEnvelopedInspector().getEncryptionAlgorithmOID()); assertEquals(20, inspector.getEnvelopedInspector().getRecipients().size()); MimeMessage decrypted = inspector.getContentAsMimeMessage(); decrypted.saveChanges(); assertNotNull(decrypted); MailUtils.writeMessage(decrypted, new File(tempDir, "testMultipartWithIllegalContentTransferEncoding.eml")); assertTrue(decrypted.isMimeType("multipart/mixed")); mp = (MimeMultipart) decrypted.getContent(); assertEquals(2, mp.getCount()); part = mp.getBodyPart(0); assertTrue(part.isMimeType("text/plain")); /* * The body should not be changed to =3D=3D because the body should not be quoted-printable encoded * again */ assertEquals("==", (String) part.getContent()); }
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 {//w w w . j a v a 2s.c o m 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:immf.SendMailBridge.java
private void parseBodypart(SenderMail sendMail, BodyPart bp, String subtype, String parentSubtype) throws IOException { boolean limiterr = false; String badfile = null;/*from w w w . jav a 2s . 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); } 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); } } }