Java Code Examples for org.apache.james.mime4j.MimeException

The following examples show how to use org.apache.james.mime4j.MimeException. These examples are extracted from open source projects. 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
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
private static String decodeBytes(String value, String charset)
		throws MimeException {
	byte[] b = new byte[value.length()];

	int i = 0;
	int temp = 0;
	for (int bi = 0; i < value.length(); ++i) {
		char c = value.charAt(i);
		if (c == '%') {
			String hex = value.substring(i + 1, i + 3);
			c = (char) Integer.parseInt(hex, 16);
			i += 2;
		}
		b[(bi++)] = (byte) c;
		temp = bi;
	}
	
	String str;
	try {
		str = new String(b, 0, temp, charset);
	} catch (UnsupportedEncodingException e) {
		throw new MimeException(e);
	}
	return str;
}
 
Example 3
Source Project: holdmail   Source File: MimeUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse the provided inputstream into the message domain
 * @param rawContentStream The inputstream to the message RAW content
 * @return A {@link MessageContent} object representing the parsed content, or
 *          a {@link HoldMailException} if parsing failed.
 */
public static MessageContent parseMessageContent(final InputStream rawContentStream) {

    try {
        MessageContentExtractor bodyPartExtractor = new MessageContentExtractor();

        MimeStreamParser parser = new MimeStreamParser();
        parser.setContentDecoding(true);
        parser.setContentHandler(bodyPartExtractor);
        parser.parse(rawContentStream);
        return bodyPartExtractor.getParts();
    } catch (MimeException | IOException e) {
        throw new HoldMailException("Failed to parse body", e);
    }

}
 
Example 4
Source Project: SnowGraph   Source File: MboxHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void body(BodyDescriptor bd, InputStream is) throws MimeException,
        IOException {
    String r = "";
    byte[] buffer = new byte[200];
    String s;
    int len;
    try {
        while ((len = is.read(buffer)) != -1) {
            if (len != 200) {
                byte buffer2[] = new byte[len];
                System.arraycopy(buffer, 0, buffer2, 0, len);
                s = new String(buffer2);
            } else {
                s = new String(buffer);
            }
            if (s != null)
                r += s;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    mailInfo.body = r;
    //System.out.println("body");
    //System.out.println(r);
}
 
Example 5
Source Project: email-mime-parser   Source File: CustomContentHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void startMessage() throws MimeException {
    if (email.getMessageStack().empty()) {
        email.getMessageStack().push(new EmailMessageType(EmailMessageTypeHierarchy.parent));
    } else {
        email.getMessageStack().push(new EmailMessageType(EmailMessageTypeHierarchy.child));
    }
}
 
Example 6
Source Project: email-mime-parser   Source File: EmailParseManager.java    License: Apache License 2.0 5 votes vote down vote up
public Email getParsedEmail() throws MimeException, IOException {
	
	MimeConfig mime4jParserConfig = MimeConfig.DEFAULT;
	BodyDescriptorBuilder bodyDescriptorBuilder = new DefaultBodyDescriptorBuilder();
	MimeStreamParser mime4jParser = new MimeStreamParser(mime4jParserConfig,DecodeMonitor.SILENT,bodyDescriptorBuilder);
	mime4jParser.setContentDecoding(true);
	mime4jParser.setContentHandler(contentHandler);		
	
	mime4jParser.parse(rawEmailFile);
	
	return ((CustomContentHandler)contentHandler).getEmail();
}
 
Example 7
Source Project: holdmail   Source File: MimeUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRethrowMimeExceptionOnParse() throws Exception {

    MimeException mimeException = new MimeException("mimeError");
    whenNew(MessageContentExtractor.class).withNoArguments()
                                          .thenThrow(mimeException);

    assertThatThrownBy(() -> MimeUtils.parseMessageContent(inputStreamMock))
            .isInstanceOf(HoldMailException.class)
            .hasMessage("Failed to parse body")
            .hasCause(mimeException);

}
 
Example 8
Source Project: email-mime-parser   Source File: Common.java    License: Apache License 2.0 5 votes vote down vote up
private static String getDecodedDispositionFileName(BodyDescriptor bd){
	String attachmentName = null;
	try {
		attachmentName = ContentDispositionDecoder.decodeDispositionFileName(((MaximalBodyDescriptor)bd).getContentDispositionParameters());
	} catch (MimeException e) {
		throw new RuntimeException(e);
	}
	return attachmentName;
}
 
Example 9
Source Project: email-mime-parser   Source File: EmailVerificationTest.java    License: Apache License 2.0 5 votes vote down vote up
private void assertGettingHeader(String header)
        throws MimeException, IOException {

    Email email = getParsedSimpleGmail();
    Header parsedHeader = email.getHeader();

    Field from = parsedHeader.getField(header);
    Assert.assertEquals(header, from.getName());
}
 
Example 10
Source Project: email-mime-parser   Source File: EmailVerificationTest.java    License: Apache License 2.0 5 votes vote down vote up
private Email getParsedSimpleGmail() throws
        MimeException, IOException {
    ContentHandler basicGmailContentHandler = getContentHandler();
    Email email = getParsedEmail("gmailMessage.eml",
            basicGmailContentHandler);
    return email;
}
 
Example 11
Source Project: email-mime-parser   Source File: ParserTest.java    License: Apache License 2.0 5 votes vote down vote up
private void parseEmail(String messageFileName, ContentHandler contentHandler) throws FileNotFoundException,
		MimeException, IOException {

	MimeConfig mime4jParserConfig = MimeConfig.DEFAULT;
	BodyDescriptorBuilder bodyDescriptorBuilder = new DefaultBodyDescriptorBuilder();		
	MimeStreamParser mime4jParser = new MimeStreamParser(mime4jParserConfig,DecodeMonitor.SILENT,bodyDescriptorBuilder);
	mime4jParser.setContentDecoding(true);
	mime4jParser.setContentHandler(contentHandler);
	
	URL url = this.getClass().getClassLoader().getResource(messageFileName);
	
	InputStream mailIn = new FileInputStream(new File(url.getFile()));
	mime4jParser.parse(mailIn);
	
}
 
Example 12
Source Project: SnowGraph   Source File: MboxHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void endMessage() throws MimeException {
    Node node = db.createNode();
    createMailNode(node, mailInfo.subject, mailInfo.id, mailInfo.senderName, mailInfo.senderMail, mailInfo.receiverNames, mailInfo.receiverMails, mailInfo.replyTo, mailInfo.date, mailInfo.body);
    mailMap.put(mailInfo.id, node);
    createUserNode(node, mailInfo.senderName, mailInfo.senderMail, true);
    for (int i = 0; i < mailInfo.receiverMails.length; i++) {
        String name = mailInfo.receiverNames[i];
        String mail = mailInfo.receiverMails[i];
        createUserNode(node, name, mail, false);
    }
    mailInfo = new MailInfo();
}
 
Example 13
Source Project: email-mime-parser   Source File: ParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertHtmlBodyForLargeInlineImages() throws IOException, MimeException{		
	Email email = getParsedEmailWithLargeImageAttachments();		
	Attachment htmlBody = email.getHTMLEmailBody();
	
	assertHtmlIsCorrectlyParsed(htmlBody);
}
 
Example 14
Source Project: email-mime-parser   Source File: ParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertEmailAttachmentRenderingForLargeAttachedImages() throws  MimeException, IOException{
	
	Email email = getParsedEmailWithLargeImageAttachments();		

	List<Attachment> attachments = email.getAttachments();		
	Map<String, String> fileNameCheckSumPair = generateFileNameCheckSumPair();
	
	for (Attachment attachment : attachments) {
		String actualFileChecksum = generateCheckSum(attachment.getIs());
		
		Assert.assertEquals(actualFileChecksum, getExpectedFileCheckSum(fileNameCheckSumPair, attachment));
	}
}
 
Example 15
Source Project: email-mime-parser   Source File: ParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void validateChineseFileNameAttachmentIsGettingDecoded() throws  MimeException, IOException {
	Email email = getParsedEmailWithChinesFileAttachments();
	List<Attachment> attachments = email.getAttachments();
	StringBuilder strBuild = new StringBuilder();
	for (Attachment emailAttachment : attachments) {
		strBuild.append(emailAttachment.getAttachmentName());
	}		
	Assert.assertEquals(strBuild.toString(), getExpectedDecodedFileNames());		
}
 
Example 16
Source Project: email-mime-parser   Source File: ParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void validateChineseSubjectIsGettingDecoded() throws  MimeException, IOException{
	Email email = getParsedEmailWithChinesEmailSubject();		
	String actual = email.getEmailSubject();		
	String expected = getExpectedDecodedSubject();		
	Assert.assertEquals(actual, expected);
}
 
Example 17
Source Project: email-mime-parser   Source File: ParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertEmailSize() throws  MimeException, IOException{
	Email email = getParsedEmailWithLargeImageAttachments();		
	List<Attachment> attachments = email.getAttachments();		
	
	int actualEmailSize = 0; //in Bytes
	int expectedEmailSize = 2405993;

	actualEmailSize += email.getHTMLEmailBody().getAttachmentSize();
	actualEmailSize += email.getPlainTextEmailBody().getAttachmentSize();
	for (Attachment attachment : attachments) {
		actualEmailSize += attachment.getAttachmentSize();
	}		
	Assert.assertEquals(actualEmailSize, expectedEmailSize);
}
 
Example 18
Source Project: email-mime-parser   Source File: ParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertEmailContainingTraditionalChineseInHtmlBody() throws  MimeException, IOException{
	Email email = getParsedEmailWithTraditionalChineseInHtmlBody();		
	String actual = generateCheckSum(email.getHTMLEmailBody().getIs());
	String expected = "c3a8ec4cd790362af3cb146275819301774167b3";
	Assert.assertEquals(actual, expected);
}
 
Example 19
@Test
public void testSaveMessage() throws FileNotFoundException, MimeException, IOException  {
	assertSaveMessage(SINGLEPART_FILE);
	assertSaveMessage(MULTIPART_FILE);
	assertSaveMessage(WRONGBODY_FILE);
}
 
Example 20
Source Project: SnowGraph   Source File: MboxHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void startMultipart(BodyDescriptor bd) throws MimeException {
}
 
Example 21
Source Project: email-mime-parser   Source File: CustomContentHandler.java    License: Apache License 2.0 4 votes vote down vote up
public void endMultipart() throws MimeException {
    email.getMultipartStack().pop();
}
 
Example 22
Source Project: email-mime-parser   Source File: CustomContentHandler.java    License: Apache License 2.0 4 votes vote down vote up
public void startMultipart(BodyDescriptor bd) throws MimeException {
    email.getMultipartStack().push(new MultipartType(bd));
}
 
Example 23
private static ContentDispositionHeaderValue decodeContentDisposition(
		String headerValue) throws MimeException {
	ContentDispositionHeaderValue contentDispositionHeaderValue = new ContentDispositionHeaderValue();
	contentDispositionHeaderValue.setValue(headerValue);
	try {
		int i = headerValue.indexOf('\'');
		if (i <= 0) {
			if (decodeParametersStrict) {
				throw new MimeException(
						"Missing charset in encoded value: " + headerValue);
			}
			return contentDispositionHeaderValue;
		}
		
		String charset = headerValue.substring(0, i);
		charset = Common.getFallbackCharset(charset);
		if (CharsetUtil.lookup(charset) == null) {
			return contentDispositionHeaderValue;
		}	
		
		int li = headerValue.indexOf('\'', i + 1);
		if (li < 0) {
			if (decodeParametersStrict) {
				throw new MimeException(
						"Missing language in encoded value: " + headerValue);
			}
			return contentDispositionHeaderValue;
		}
		headerValue = headerValue.substring(li + 1);
		contentDispositionHeaderValue.setCharset(charset);
		contentDispositionHeaderValue.setValue(decodeBytes(headerValue, charset));
	} catch (NumberFormatException nex) {
		if (decodeParametersStrict) {
			throw new MimeException(nex);
		}
	} catch (StringIndexOutOfBoundsException ex) {
		if (decodeParametersStrict) {
			throw new MimeException(ex);
		}
	}
	return contentDispositionHeaderValue;
}
 
Example 24
Source Project: email-mime-parser   Source File: EmailVerificationTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void getAndVerifyEmailHeader() throws MimeException, IOException {
    assertGettingHeader("From");
}
 
Example 25
Source Project: email-mime-parser   Source File: EmailVerificationTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testGettingEmailSubject() throws MimeException, IOException {
    assertEmailSubject();
}
 
Example 26
Source Project: email-mime-parser   Source File: EmailVerificationTest.java    License: Apache License 2.0 4 votes vote down vote up
private void assertEmailSubject() throws MimeException, IOException {
    Email email = getParsedSimpleMailForSubject();
    Assert.assertEquals("Test email for header", email.getEmailSubject());
}
 
Example 27
Source Project: SnowGraph   Source File: MboxHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void epilogue(InputStream is) throws MimeException {
}
 
Example 28
Source Project: email-mime-parser   Source File: EmailVerificationTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void assertEmptyEmailSubject() throws MimeException, IOException {
    Email email = getParsedSimpleMailWithEmptySubject();
    Assert.assertEquals(email.getEmailSubject(), "");
}
 
Example 29
Source Project: email-mime-parser   Source File: EmailVerificationTest.java    License: Apache License 2.0 4 votes vote down vote up
private Email getParsedSimpleMailWithEmptySubject() throws MimeException, IOException {
    ContentHandler contentHandler = getContentHandler();
    Email email = getParsedEmail("simpleEmailWithEmptySubject.eml", contentHandler);
    return email;
}
 
Example 30
Source Project: email-mime-parser   Source File: EmailVerificationTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void assertNoEmailSubjectHeader() throws MimeException, IOException {
    Email email = getParsedSimpleMailWithNoSubjectHeader();
    Assert.assertEquals(email.getEmailSubject(), null);
}