org.apache.james.mime4j.message.DefaultMessageBuilder Java Examples

The following examples show how to use org.apache.james.mime4j.message.DefaultMessageBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MessageStoreImplRepositoryTest.java    From sling-samples with Apache License 2.0 6 votes vote down vote up
private void assertSaveMessage(String messageFile) throws MimeException, IOException, FileNotFoundException {
	MessageBuilder builder = new DefaultMessageBuilder();
	Message msg = builder.parseMessage(new FileInputStream(new File(TU.TEST_FOLDER, messageFile)));

	store.save(msg);

	final Resource r = resolver.getResource(getResourcePath(msg, store));
	assertNotNull("Expecting non-null Resource", r);
	final ModifiableValueMap m = r.adaptTo(ModifiableValueMap.class);

	File bodyFile = new File(TU.TEST_FOLDER, specialPathFromFilePath(messageFile, BODY_SUFFIX));
	if (bodyFile.exists()) {
		String expectedBody = readTextFile(bodyFile);
		assertValueMap(m, "Body", expectedBody);
	}

	File headersFile = new File(TU.TEST_FOLDER, specialPathFromFilePath(messageFile, HEADERS_SUFFIX));
	if (headersFile.exists()) {
		MessageStoreImplRepositoryTestUtil.assertHeaders(headersFile, m);
	}

	assertTrue(headersFile.exists() || bodyFile.exists()); // test at least something 
}
 
Example #2
Source File: MessageParser.java    From james-project with Apache License 2.0 6 votes vote down vote up
public List<ParsedAttachment> retrieveAttachments(InputStream fullContent) throws IOException {
    DefaultMessageBuilder defaultMessageBuilder = new DefaultMessageBuilder();
    defaultMessageBuilder.setMimeEntityConfig(MimeConfig.PERMISSIVE);
    defaultMessageBuilder.setDecodeMonitor(DecodeMonitor.SILENT);
    Message message = defaultMessageBuilder.parseMessage(fullContent);
    Body body = message.getBody();
    try {
        if (isAttachment(message, Context.BODY)) {
            return ImmutableList.of(retrieveAttachment(message));
        }

        if (body instanceof Multipart) {
            Multipart multipartBody = (Multipart) body;
            return listAttachments(multipartBody, Context.fromSubType(multipartBody.getSubType()))
                .collect(Guavate.toImmutableList());
        } else {
            return ImmutableList.of();
        }
    } finally {
        body.dispose();
    }
}
 
Example #3
Source File: DnsMailCreatorLargeOriginalTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@Test
public void testLongMail() throws Exception {
    DsnMailCreator dsnMailCreator =
            DsnMailCreatorTest.createDsnMailCreator();
    Mail mail = ExampleMail.veryLong();
    List<RecipientProblemReport> recipientStatuses =
            DsnMailCreatorTest.createRecipientFailure();
    Mail dsnMail = dsnMailCreator.create(mail, recipientStatuses);

    File file =
            new File(System.getProperty("java.io.tmpdir"), getClass()
                    .getSimpleName() + ".eml");
    FileOutputStream fout = new FileOutputStream(file);
    dsnMail.mailData.writeTo(fout);
    fout.close();

    FileInputStream in = new FileInputStream(file);
    Message message = new DefaultMessageBuilder().parseMessage(in);
    in.close();
    assertEquals(message.getMimeType(), "multipart/report");
    file.delete();
}
 
Example #4
Source File: DsnMailCreatorTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreate() throws Exception {
    DsnMailCreator dsnMailCreator = createDsnMailCreator();
    Mail mail = ExampleMail.simple();
    List<RecipientProblemReport> recipientStatuses =
            createRecipientFailure();
    Mail dsnMail = dsnMailCreator.create(mail, recipientStatuses);

    writeToFileForDebugging(dsnMail.mailData);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    dsnMail.mailData.writeTo(out);
    byte[] bytes = out.toByteArray();
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    Message message = new DefaultMessageBuilder().parseMessage(in);
    assertEquals(message.getMimeType(), "multipart/report");
}
 
Example #5
Source File: ResponseDecoder.java    From NioImapClient with Apache License 2.0 5 votes vote down vote up
public ResponseDecoder(ImapClientConfiguration configuration,
                       ImapClientState clientState,
                       EventExecutorGroup executorGroup) {
  super(State.SKIP_CONTROL_CHARS);
  this.logger = LogUtils.loggerWithName(ResponseDecoder.class, clientState.getClientName());
  this.clientState = clientState;
  this.executorGroup = executorGroup;

  this.charSeq = new SoftReferencedAppendableCharSequence(configuration.defaultResponseBufferSize());
  this.lineParser = new LineParser(charSeq, configuration.maxLineLength());
  this.wordParser = new WordParser(charSeq, configuration.maxLineLength());
  this.fetchResponseTypeParser = new FetchResponseTypeParser(charSeq, configuration.maxLineLength());
  this.atomOrStringParser = new AtomOrStringParser(charSeq, configuration.maxLineLength());
  this.literalStringParser = new LiteralStringParser(charSeq, configuration.maxLineLength());
  this.bufferedBodyParser = new BufferedBodyParser(charSeq);
  this.numberParser = new NumberParser(charSeq, 19);
  this.envelopeParser = new EnvelopeParser();
  this.nestedArrayParserRecycler = new NestedArrayParser.Recycler<>(literalStringParser);
  this.messageBuilder = ((DefaultMessageBuilder) MESSAGE_SERVICE_FACTORY.newMessageBuilder());

  MimeConfig mimeConfig = MimeConfig.custom()
      .setMaxLineLen(configuration.maxLineLength())
      .setMaxHeaderLen(configuration.maxLineLength())
      .setMaxHeaderCount(configuration.maxHeaderCount())
      .build();

  messageBuilder.setMimeEntityConfig(mimeConfig);

  this.untaggedResponses = new ArrayList<>();
  this.responseBuilder = new TaggedResponse.Builder();

  this.allBytesParser = configuration.tracingEnabled() ? new AllBytesParser(charSeq) : null;
}
 
Example #6
Source File: MboxReader.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected void doInitialize(UimaContext context) throws ResourceInitializationException {

  // Initialise charset for MBOX processing
  try {
    charset = Charset.forName(charsetName);
  } catch (UnsupportedCharsetException | IllegalCharsetNameException ce) {
    getMonitor().warn("Unsupported charset, {}. UTF-8 will be used.", charsetName, ce);
    charset = StandardCharsets.UTF_8;
  }

  // Initialise MBOX iterator
  try {
    mboxIterator =
        MboxIterator.fromFile(mbox)
            .charset(charset)
            .maxMessageSize(messageSize)
            .build()
            .iterator();
  } catch (IOException ioe) {
    throw new ResourceInitializationException(ioe);
  }

  // Initialise message parser
  messageBuilder = new DefaultMessageBuilder();
  messageBuilder.setContentDecoding(true);

  MimeConfig config = new MimeConfig.Builder().setMaxLineLen(10000).build();
  messageBuilder.setMimeEntityConfig(config);

  // Build list of extensions to ignore
  for (String s : ignoreExtensions) {
    ignoreExtensionsList.add(s.trim().toLowerCase());
  }
}
 
Example #7
Source File: DeletedMessageConverter.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Optional<Message> parseMessage(org.apache.james.mailbox.store.mail.model.Message message) throws IOException {
    DefaultMessageBuilder messageBuilder = new DefaultMessageBuilder();
    messageBuilder.setMimeEntityConfig(MimeConfig.PERMISSIVE);
    messageBuilder.setDecodeMonitor(DecodeMonitor.SILENT);
    try {
        return Optional.ofNullable(messageBuilder.parseMessage(message.getFullContent()));
    } catch (MimeIOException e) {
        LOGGER.warn("Can not parse the message {}", message.getMessageId(), e);
        return Optional.empty();
    }
}
 
Example #8
Source File: MessageSearches.java    From james-project with Apache License 2.0 5 votes vote down vote up
private HeaderImpl buildTextHeaders(MailboxMessage message) throws IOException, MimeIOException {
    DefaultMessageBuilder defaultMessageBuilder = new DefaultMessageBuilder();
    defaultMessageBuilder.setMimeEntityConfig(MimeConfig.PERMISSIVE);
    Message headersMessage = defaultMessageBuilder
        .parseMessage(message.getHeaderContent());
    HeaderImpl headerImpl = new HeaderImpl();
    addFrom(headerImpl, headersMessage.getFrom());
    addAddressList(headerImpl, headersMessage.getTo());
    addAddressList(headerImpl, headersMessage.getCc());
    addAddressList(headerImpl, headersMessage.getBcc());
    headerImpl.addField(Fields.subject(headersMessage.getSubject()));
    return headerImpl;
}
 
Example #9
Source File: ExtractMDNOriginalJMAPMessageId.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Optional<Message> parseMessage(MimeMessage mimeMessage) {
    LOGGER.debug("Parsing message");
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        mimeMessage.writeTo(os);
        Message message = new DefaultMessageBuilder().parseMessage(new ByteArrayInputStream(os.toByteArray()));
        return Optional.of(message);
    } catch (IOException | MessagingException e) {
        LOGGER.error("unable to parse message", e);
        return Optional.empty();
    }
}
 
Example #10
Source File: SendMDNProcessor.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Message retrieveOriginalMessage(JmapMDN mdn, MailboxSession mailboxSession) throws MailboxException, IOException, MessageNotFoundException {
    List<MessageResult> messages = messageIdManager.getMessage(mdn.getMessageId(), FetchGroup.HEADERS, mailboxSession);

    if (messages.size() == 0) {
        throw new MessageNotFoundException();
    }

    DefaultMessageBuilder messageBuilder = new DefaultMessageBuilder();
    messageBuilder.setMimeEntityConfig(MimeConfig.PERMISSIVE);
    messageBuilder.setDecodeMonitor(DecodeMonitor.SILENT);
    return messageBuilder.parseMessage(messages.get(0).getHeaders().getInputStream());
}
 
Example #11
Source File: EnvelopeTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Message toMime4JMessage(String messageAsString) throws IOException {
    DefaultMessageBuilder defaultMessageBuilder = new DefaultMessageBuilder();
    defaultMessageBuilder.setMimeEntityConfig(MimeConfig.PERMISSIVE);
    defaultMessageBuilder.setDecodeMonitor(DecodeMonitor.SILENT);
    return defaultMessageBuilder.parseMessage(
        new ByteArrayInputStream(messageAsString.getBytes(StandardCharsets.UTF_8)));
}