List of usage examples for javax.mail Message getSubject
public abstract String getSubject() throws MessagingException;
From source file:org.apache.oodt.cas.crawl.action.EmailNotification.java
@Override public boolean performAction(File product, Metadata metadata) throws CrawlerActionException { try {//from www . j a v a2s .c o m Properties props = new Properties(); props.put("mail.host", this.mailHost); props.put("mail.transport.protocol", "smtp"); props.put("mail.from", this.sender); Session session = Session.getDefaultInstance(props); Message msg = new MimeMessage(session); msg.setSubject(PathUtils.doDynamicReplacement(subject, metadata)); msg.setText(new String(PathUtils.doDynamicReplacement(message, metadata).getBytes())); for (String recipient : recipients) { try { msg.addRecipient(Message.RecipientType.TO, new InternetAddress( PathUtils.replaceEnvVariables(recipient.trim(), metadata), ignoreInvalidAddresses)); LOG.fine("Recipient: " + PathUtils.replaceEnvVariables(recipient.trim(), metadata)); } catch (AddressException ae) { LOG.fine("Recipient: " + PathUtils.replaceEnvVariables(recipient.trim(), metadata)); LOG.warning(ae.getMessage()); } } LOG.fine("Subject: " + msg.getSubject()); LOG.fine("Message: " + new String(PathUtils.doDynamicReplacement(message, metadata).getBytes())); Transport.send(msg); return true; } catch (Exception e) { LOG.severe(e.getMessage()); return false; } }
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
private EmailMessage wrapMessage(Message msg, boolean populateContent, Session session) throws MessagingException, IOException, ScanException, PolicyException { // Prepare subject String subject = msg.getSubject(); if (!StringUtils.isBlank(subject)) { AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(subject, policy); subject = cr.getCleanHTML();/*from w ww . j av a 2 s. c om*/ } // Prepare content if requested EmailMessageContent msgContent = null; // default... if (populateContent) { // Defend against the dreaded: "Unable to load BODYSTRUCTURE" try { msgContent = getMessageContent(msg.getContent(), msg.getContentType()); } catch (MessagingException me) { // We are unable to read digitally-signed messages (perhaps // others?) in the API-standard way; we have to use a work around. // See: http://www.oracle.com/technetwork/java/faq-135477.html#imapserverbug // Logging as DEBUG because this behavior is known & expected. log.debug("Difficulty reading a message (digitally signed?). Attempting workaround..."); try { MimeMessage mm = (MimeMessage) msg; ByteArrayOutputStream bos = new ByteArrayOutputStream(); mm.writeTo(bos); bos.close(); SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray()); MimeMessage copy = new MimeMessage(session, bis); bis.close(); msgContent = getMessageContent(copy.getContent(), copy.getContentType()); } catch (Throwable t) { log.error("Failed to read message body", t); msgContent = new EmailMessageContent("UNABLE TO READ MESSAGE BODY: " + t.getMessage(), false); } } // Sanitize with AntiSamy String content = msgContent.getContentString(); if (!StringUtils.isBlank(content)) { AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(content, policy); content = cr.getCleanHTML(); } msgContent.setContentString(content); } int messageNumber = msg.getMessageNumber(); // Prepare the UID if present String uid = null; // default if (msg.getFolder() instanceof UIDFolder) { uid = Long.toString(((UIDFolder) msg.getFolder()).getUID(msg)); } Address[] addr = msg.getFrom(); String sender = getFormattedAddresses(addr); Date sentDate = msg.getSentDate(); boolean unread = !msg.isSet(Flag.SEEN); boolean answered = msg.isSet(Flag.ANSWERED); boolean deleted = msg.isSet(Flag.DELETED); // Defend against the dreaded: "Unable to load BODYSTRUCTURE" boolean multipart = false; // sensible default; String contentType = null; // sensible default try { multipart = msg.getContentType().toLowerCase().startsWith(CONTENT_TYPE_ATTACHMENTS_PATTERN); contentType = msg.getContentType(); } catch (MessagingException me) { // Message was digitally signed and we are unable to read it; // logging as DEBUG because this issue is known/expected, and // because the user's experience is in no way affected (at this point) log.debug("Message content unavailable (digitally signed?); " + "message will appear in the preview table correctly, " + "but the body will not be viewable"); log.trace(me.getMessage(), me); } String to = getTo(msg); String cc = getCc(msg); String bcc = getBcc(msg); return new EmailMessage(messageNumber, uid, sender, subject, sentDate, unread, answered, deleted, multipart, contentType, msgContent, to, cc, bcc); }
From source file:org.apache.usergrid.rest.management.AdminUsersIT.java
@Test public void checkPasswordChangeTime() throws Exception { // request password reset management().users().user(clientSetup.getUsername()).resetpw().post(new Form()); refreshIndex();/* w ww. jav a2 s . com*/ // get resetpw token from email List<Message> inbox = Mailbox.get(clientSetup.getEmail()); assertFalse(inbox.isEmpty()); MockImapClient client = new MockImapClient("mockserver.com", "test-user-46", "somepassword"); client.processMail(); String token = null; Iterator<Message> msgIterator = inbox.iterator(); while (token == null && msgIterator.hasNext()) { Message msg = msgIterator.next(); if (msg.getSubject().equals("Password Reset")) { token = getTokenFromMessage(msg); } } assertNotNull(token); // reset the password to sesame Form formData = new Form(); formData.param("token", token); formData.param("password1", "sesame"); formData.param("password2", "sesame"); String html = management().users().user(clientSetup.getUsername()).resetpw().getTarget().request() .post(javax.ws.rs.client.Entity.form(formData), String.class); assertTrue(html.contains("password set")); refreshIndex(); // login with new password and get token Map<String, Object> payload = new HashMap<String, Object>() { { put("grant_type", "password"); put("username", clientSetup.getUsername()); put("password", "sesame"); } }; ApiResponse response = management().token().post(false, payload, null); // check password changed time Long changeTime = Long.parseLong(response.getProperties().get("passwordChanged").toString()); assertTrue(System.currentTimeMillis() - changeTime < 2000); // change password again by posting JSON payload = new HashMap<String, Object>() { { put("oldpassword", "sesame"); put("newpassword", "test"); } }; management().users().user(clientSetup.getUsername()).password().post(false, payload, null); refreshIndex(); // get password and check password change time again payload = new HashMap<String, Object>() { { put("grant_type", "password"); put("username", clientSetup.getUsername()); put("password", "test"); } }; response = management().token().post(false, payload, null); Long changeTime2 = Long.parseLong(response.getProperties().get("passwordChanged").toString()); assertTrue(changeTime < changeTime2); assertTrue(System.currentTimeMillis() - changeTime2 < 2000); // login via /me end-point and check password change time again response = management().me().get(ApiResponse.class, new QueryParameters().addParam("grant_type", "password") .addParam("username", clientSetup.getUsername()).addParam("password", "test")); Long changeTime3 = Long.parseLong(response.getProperties().get("passwordChanged").toString()); assertEquals(changeTime2, changeTime3); }
From source file:com.openkm.util.MailUtils.java
/** * Import mail into OpenKM repository/*w ww . ja v a 2 s . c om*/ */ public static void importMail(String token, String mailPath, boolean grouping, Folder folder, Message msg, MailAccount ma, com.openkm.bean.Mail mail) throws DatabaseException, RepositoryException, AccessDeniedException, ItemExistsException, PathNotFoundException, MessagingException, VirusDetectedException, UserQuotaExceededException, IOException, ExtensionException, AutomationException { OKMRepository okmRepository = OKMRepository.getInstance(); String path = grouping ? createGroupPath(token, mailPath, mail.getReceivedDate()) : mailPath; if (ma.getMailProtocol().equals(MailAccount.PROTOCOL_POP3) || ma.getMailProtocol().equals(MailAccount.PROTOCOL_POP3S)) { mail.setPath(path + "/" + ((POP3Folder) folder).getUID(msg) + "-" + PathUtils.escape( (msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject())); } else { mail.setPath(path + "/" + ((IMAPFolder) folder).getUID(msg) + "-" + PathUtils.escape( (msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject())); } String newMailPath = PathUtils.getParent(mail.getPath()) + "/" + PathUtils.escape(PathUtils.getName(mail.getPath())); log.debug("newMailPath: {}", newMailPath); if (!okmRepository.hasNode(token, newMailPath)) { if (Config.REPOSITORY_NATIVE) { new DbMailModule().create(token, mail, ma.getUser(), new Ref<FileUploadResponse>(null)); } else { new JcrMailModule().create(token, mail, ma.getUser()); } try { addAttachments(token, mail, msg, ma.getUser()); } catch (UnsupportedMimeTypeException e) { log.warn(e.getMessage(), e); } catch (FileSizeExceededException e) { log.warn(e.getMessage(), e); } catch (UserQuotaExceededException e) { log.warn(e.getMessage(), e); } } }
From source file:com.cubusmail.mail.MessageHandler.java
/** * @param msg//from ww w . ja va2 s . c om * @throws MessagingException * @throws IOException */ public void createForwardMessage(Message msg) throws MessagingException, IOException { init(); setSubject("Fwd: " + msg.getSubject()); setHtmlMessage(MessageUtils.isHtmlMessage(msg)); List<MimePart> attachments = MessageUtils.attachmentsFromPart(msg); if (attachments != null) { for (MimePart part : attachments) { DataSource source = part.getDataHandler().getDataSource(); ByteArrayDataSource newSource = new ByteArrayDataSource(source.getInputStream(), source.getContentType()); if (StringUtils.isEmpty(source.getName())) { newSource.setName(this.applicationContext.getMessage("message.unknown.attachment", null, SessionManager.get().getLocale())); } else { newSource.setName(source.getName()); } addComposeAttachment(newSource); } } Preferences prefs = SessionManager.get().getPreferences(); MessageTextUtil.messageTextFromPart(msg, this, true, MessageTextMode.REPLY, prefs, 0); }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * Retrieve mail messages in a JSON representation * //from ww w.j a v a 2 s.c o m * @return */ public JSONArray getJMessages() { JSONArray jMessages = new JSONArray(); if (store == null) return jMessages; try { /* * Connect to IMAP store */ store.connect(); /* * Retrieve & open INBOX folder */ Folder folder = store.getFolder(ImapConstants.INBOX); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { Message m = messages[i]; JSONObject jMessage = new JSONObject(); jMessage.put(ImapConstants.J_KEY, ""); // introduced to be compatible with posted emails jMessage.put(ImapConstants.J_ID, i); // message identifier to retrieve from external server jMessage.put(ImapConstants.J_SUBJECT, m.getSubject()); jMessage.put(ImapConstants.J_DATE, m.getSentDate()); String from = ""; Address[] addresses = m.getFrom(); for (Address address : addresses) { InternetAddress internetAddress = (InternetAddress) address; from = internetAddress.getPersonal(); } jMessage.put(ImapConstants.J_FROM, from); FileUtil attachment = getAttachment(m); if (attachment == null) { jMessage.put(ImapConstants.J_ATTACHMENT, false); } else { jMessage.put(ImapConstants.J_ATTACHMENT, true); } jMessages.put(jMessages.length(), jMessage); } folder.close(false); store.close(); } catch (Exception e) { e.printStackTrace(); } finally { } return jMessages; }
From source file:org.apache.usergrid.rest.management.AdminUsersIT.java
/** * Test that a unconfirmed admin cannot log in. * TODO:test for parallel test that changing the properties here won't affect other tests * @throws Exception/*from w ww .j a va2 s .com*/ */ @Test public void testUnconfirmedAdminLogin() throws Exception { ApiResponse originalTestPropertiesResponse = clientSetup.getRestClient().testPropertiesResource().get(); Entity originalTestProperties = new Entity(originalTestPropertiesResponse); try { //Set runtime enviroment to the following settings //TODO: make properties verification its own test. Map<String, Object> testPropertiesMap = new HashMap<>(); testPropertiesMap.put(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "false"); testPropertiesMap.put(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false"); //Requires admins to do email confirmation before they can log in. testPropertiesMap.put(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "true"); testPropertiesMap.put(PROPERTIES_DEFAULT_SYSADMIN_EMAIL, "sysadmin-1@mockserver.com"); Entity testPropertiesPayload = new Entity(testPropertiesMap); //Send rest call to the /testProperties endpoint to persist property changes clientSetup.getRestClient().testPropertiesResource().post(testPropertiesPayload); refreshIndex(); //Create organization for the admin user to be confirmed Organization organization = createOrgPayload("testUnconfirmedAdminLogin", null); Organization organizationResponse = clientSetup.getRestClient().management().orgs().post(organization); assertNotNull(organizationResponse); //Ensure that adminUser has the correct properties set. User adminUser = organizationResponse.getOwner(); assertNotNull(adminUser); assertFalse("adminUser should not be activated yet", adminUser.getActivated()); assertFalse("adminUser should not be confirmed yet", adminUser.getConfirmed()); //Get token grant for new admin user. QueryParameters queryParameters = new QueryParameters(); queryParameters.addParam("grant_type", "password").addParam("username", adminUser.getUsername()) .addParam("password", organization.getPassword()); //Check that the adminUser cannot log in and fails with a 403 due to not being confirmed. try { management().token().get(queryParameters); fail("Admin user should not be able to log in."); } catch (ClientErrorException uie) { assertEquals("Admin user should have failed with 403", 403, uie.getResponse().getStatus()); } //Create mocked inbox List<Message> inbox = Mailbox.get(organization.getEmail()); assertFalse(inbox.isEmpty()); MockImapClient client = new MockImapClient("mockserver.com", "test-user-46", "somepassword"); client.processMail(); //Get email with confirmation token and extract token Message confirmation = inbox.get(0); assertEquals("User Account Confirmation: " + organization.getEmail(), confirmation.getSubject()); String token = getTokenFromMessage(confirmation); //Make rest call with extracted token to confirm the admin user. management().users().user(adminUser.getUuid().toString()).confirm() .get(new QueryParameters().addParam("token", token)); //Try the previous call and verify that the admin user can retrieve login token Token retToken = management().token().get(queryParameters); assertNotNull(retToken); assertNotNull(retToken.getAccessToken()); } finally { clientSetup.getRestClient().testPropertiesResource().post(originalTestProperties); } }
From source file:gov.nih.nci.firebird.service.messages.email.EmailServiceImplTest.java
@Test public void testSendMessage() throws MessagingException, IOException { bean.sendMessage(TEST_TO_ADDRESS, TEST_CC_ADDRESSES, TEST_BOUNCE_ADDRESS, testMessage); Message message = mailbox.get(0); InternetAddress fromAddress = (InternetAddress) message.getFrom()[0]; assertEquals(TEST_FROM_ADDRESS, fromAddress.getAddress()); assertEquals(TEST_FROM_NAME, fromAddress.getPersonal()); InternetAddress toAddress = (InternetAddress) message.getRecipients(RecipientType.TO)[0]; assertEquals(TEST_TO_ADDRESS, toAddress.getAddress()); assertEquals(2, message.getRecipients(RecipientType.CC).length); InternetAddress ccAddress1 = (InternetAddress) message.getRecipients(RecipientType.CC)[0]; InternetAddress ccAddress2 = (InternetAddress) message.getRecipients(RecipientType.CC)[1]; assertEquals(TEST_CC_ADDRESSES.get(0), ccAddress1.getAddress()); assertEquals(TEST_CC_ADDRESSES.get(1), ccAddress2.getAddress()); assertEquals(TEST_SUBJECT, message.getSubject()); assertEquals(TEST_CONTENT, message.getContent()); }
From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java
/** * Process bounces.//from w w w.j av a 2 s .co m * * @param protocol the protocol * @param host the host * @param port the port * @param userName the user name * @param password the password */ public void processBounces(String protocol, String host, String port, String userName, String password) { Properties properties = getServerProperties(protocol, host, port); Session session = Session.getDefaultInstance(properties); List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes(); try { // connects to the message store Store store = session.getStore(protocol); System.out.println(userName); System.out.println(password); System.out.println(userName.length()); System.out.println(password.length()); //store.connect(userName, password); //TODO: ispraviti username i password da idu iz poziva a ne hardcoded store.connect("bojan.dimic@aquest-solutions.com", "bg181076"); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { BouncedEmail bouncedEmail = new BouncedEmail(); Message msg = messages[i]; Address[] fromAddress = msg.getFrom(); String from = fromAddress[0].toString(); String failedAddress = ""; Enumeration<?> headers = messages[i].getAllHeaders(); while (headers.hasMoreElements()) { Header h = (Header) headers.nextElement(); //System.out.println(h.getName() + ":" + h.getValue()); //System.out.println(""); String mID = h.getName(); if (mID.contains("X-Failed-Recipients")) { failedAddress = h.getValue(); } } String subject = msg.getSubject(); String toList = parseAddresses(msg.getRecipients(RecipientType.TO)); String ccList = parseAddresses(msg.getRecipients(RecipientType.CC)); String sentDate = msg.getSentDate().toString(); String contentType = msg.getContentType(); String messageContent = ""; if (contentType.contains("text/plain") || contentType.contains("text/html")) { try { Object content = msg.getContent(); if (content != null) { messageContent = content.toString(); } } catch (Exception ex) { messageContent = "[Error downloading content]"; ex.printStackTrace(); } } String bounceReason = "Unknown reason"; for (BounceCode bounceCode : bounceCodes) { if (messageContent.contains(bounceCode.getCode())) { bounceReason = bounceCode.getExplanation(); } } // if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";} // if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";} // // // enhanced bounce codes // if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";} // if(messageContent.contains("5.1.0")) {bounceReason="Other address status";} // if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";} // if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";} // if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";} // if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";} // if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";} // if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";} // if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";} // print out details of each message System.out.println("Message #" + (i + 1) + ":"); System.out.println("\t From: " + from); System.out.println("\t To: " + toList); System.out.println("\t CC: " + ccList); System.out.println("\t Subject: " + subject); System.out.println("\t Sent Date: " + sentDate); System.out.println("\t X-Failed-Recipients:" + failedAddress); System.out.println("\t Content Type:" + contentType); System.out.println("\t Bounce reason:" + bounceReason); //System.out.println("\t Message: " + messageContent); bouncedEmail.setEmail_address(failedAddress); bouncedEmail.setBounce_reason(bounceReason); //Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH); //String strDate = date.toString(); System.out.println(sentDate); Date dt = null; //Date nd = null; try { dt = formatter.parse(sentDate); //nd = sqlFormat.parse(dt.toString()); } catch (ParseException e) { e.printStackTrace(); } System.out.println("Date " + dt.toString()); //System.out.println("Date " + nd.toString()); System.out.println(new Timestamp(new Date().getTime())); bouncedEmail.setSend_date(dt); bouncedEmailDao.saveOrUpdate(bouncedEmail); } // disconnect folderInbox.close(false); store.close(); } catch (NoSuchProviderException ex) { System.out.println("No provider for protocol: " + protocol); ex.printStackTrace(); } catch (MessagingException ex) { System.out.println("Could not connect to the message store"); ex.printStackTrace(); } }
From source file:com.jlgranda.fede.ejb.mail.reader.FacturaElectronicaMailReader.java
/** * Obtiene una lista de objetos <tt>FacturaReader</tt> desde el mensaje de correo, si existe * * @param mime4jMessage/*from w ww . j av a 2 s . co m*/ * @return lista de instancias instancia <tt>FacturaReader</tt> si existe la factura, null * en caso contrario */ private List<FacturaReader> handleMessage(org.apache.james.mime4j.dom.Message mime4jMessage) throws IOException, Exception { List<FacturaReader> result = new ArrayList<>(); ByteArrayOutputStream os = null; String filename = null; Factura factura = null; EmailHelper emailHelper = new EmailHelper(); if (mime4jMessage.isMultipart()) { org.apache.james.mime4j.dom.Multipart mime4jMultipart = (org.apache.james.mime4j.dom.Multipart) mime4jMessage .getBody(); emailHelper.parseBodyParts(mime4jMultipart); //Obtener la factura en los adjuntos if (emailHelper.getAttachments().isEmpty()) { //If it's single part message, just get text body String text = emailHelper.getHtmlBody().toString(); emailHelper.getTxtBody().append(text); if (mime4jMessage.getSubject().contains("Ghost")) { String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"", "\" target=\"_blank\">Descarga formato XML</a>"); if (url != null) { result.add(FacturaElectronicaURLReader.getFacturaElectronica(url)); } } } else { for (Entity entity : emailHelper.getAttachments()) { filename = EmailHelper.getFilename(entity); //if (entity.getBody() instanceof BinaryBody) { if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType()) || "application/xml".equalsIgnoreCase(entity.getMimeType()) || "text/xml".equalsIgnoreCase(entity.getMimeType()) || "text/plain".equalsIgnoreCase(entity.getMimeType())) && (filename != null && filename.endsWith(".xml"))) { //attachFiles += part.getFileName() + ", "; os = EmailHelper.writeBody(entity.getBody()); factura = FacturaUtil.read(os.toString()); if (factura != null) { result.add(new FacturaReader(factura, os.toString(), entity.getFilename(), mime4jMessage.getFrom().get(0).getAddress())); } } else if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType()) || "aplication/xml".equalsIgnoreCase(entity.getMimeType()) || "text/xml".equalsIgnoreCase(entity.getMimeType())) && (filename != null && filename.endsWith(".zip"))) { //http://www.java2s.com/Tutorial/Java/0180__File/UnzipusingtheZipInputStream.htm os = EmailHelper.writeBody(entity.getBody()); ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(os.toByteArray())); try { ZipEntry entry = null; String tmp = null; ByteArrayOutputStream fout = null; while ((entry = zis.getNextEntry()) != null) { if (entry.getName().endsWith(".xml")) { //logger.debug("Unzipping {}", entry.getFilename()); fout = new ByteArrayOutputStream(); for (int c = zis.read(); c != -1; c = zis.read()) { fout.write(c); } tmp = new String(fout.toByteArray(), Charset.defaultCharset()); factura = FacturaUtil.read(tmp); if (factura != null) { result.add(new FacturaReader(factura, tmp, entity.getFilename())); } fout.close(); } zis.closeEntry(); } zis.close(); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(zis); } } else if ("message/rfc822".equalsIgnoreCase(entity.getMimeType())) { if (entity.getBody() instanceof org.apache.james.mime4j.message.MessageImpl) { result.addAll( handleMessage((org.apache.james.mime4j.message.MessageImpl) entity.getBody())); } } } } } else { //If it's single part message, just get text body String text = emailHelper.getTxtPart(mime4jMessage); emailHelper.getTxtBody().append(text); if (mime4jMessage.getSubject().contains("Ghost")) { String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"", "\" target=\"_blank\">Descarga formato XML</a>"); if (url != null) { result.add(FacturaElectronicaURLReader.getFacturaElectronica(url)); } } } return result; }