mitm.common.mail.MailUtilsTest.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.mail.MailUtilsTest.java

Source

/*
 * Copyright (c) 2008-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, 
 * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, 
 * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, 
 * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Eclipse Public License, 
 * tyrex license, freemarker license, dom4j license, mx4j license,
 * Spice Software License, Common Development and Distribution License
 * (CDDL), Common Public License (CPL) the licensors of this Program grant 
 * you additional permission to convey the resulting work.
 */
package mitm.common.mail;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.SharedByteArrayInputStream;

import mitm.common.util.MiscStringUtils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;

import com.sun.mail.util.DecodingException;

public class MailUtilsTest {
    private static final File testBase = new File("test/resources/testdata/mail");

    private static MimeMessage loadMessage(String filename) throws FileNotFoundException, MessagingException {
        File mail = new File(testBase, filename);

        MimeMessage message = MailUtils.loadMessage(mail);

        return message;
    }

    @Test
    public void testSaveLoadedMessage() throws IOException, MessagingException {
        File outputFile = File.createTempFile("mailUtilsTest", ".eml");

        outputFile.deleteOnExit();

        MimeMessage message = loadMessage("normal-message-with-attach.eml");

        MailUtils.writeMessage(message, new FileOutputStream(outputFile));
    }

    @Test
    public void testSaveNewMessage() throws IOException, MessagingException {
        File outputFile = File.createTempFile("mailUtilsTest", ".eml");

        outputFile.deleteOnExit();

        MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

        message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
        message.addRecipients(RecipientType.TO, "recipient@example.com");
        message.setContent("test body", "text/plain");
        message.saveChanges();

        MailUtils.writeMessage(message, new FileOutputStream(outputFile));

        MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

        String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

        assertEquals("{recipient@example.com}", recipients);

        String from = ArrayUtils.toString(loadedMessage.getFrom());

        assertEquals("{test@example.com}", from);
    }

    @Test
    public void testSaveNewMessageRaw() throws IOException, MessagingException {
        File outputFile = File.createTempFile("mailUtilsTestRaw", ".eml");

        outputFile.deleteOnExit();

        MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

        message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
        message.addRecipients(RecipientType.TO, "recipient@example.com");
        message.setContent("test body", "text/plain");
        message.saveChanges();

        MailUtils.writeMessageRaw(message, new FileOutputStream(outputFile));

        MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

        String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

        assertEquals("{recipient@example.com}", recipients);

        String from = ArrayUtils.toString(loadedMessage.getFrom());

        assertEquals("{test@example.com}", from);
    }

    @Test
    public void testLoadMessage() throws FileNotFoundException, MessagingException {
        MimeMessage message = loadMessage("normal-message-with-attach.eml");

        assertTrue(message.isMimeType("multipart/mixed"));
    }

    @Test
    public void testValidateMessage() throws IOException, MessagingException {
        MimeMessage message = loadMessage("normal-message-with-attach.eml");

        MailUtils.validateMessage(message);
    }

    /*
     * Since Javamail 1.4.4 validating a message with a corrupt base64 encoded attachment no longer fails. Javamail 
     * 1.4.4 does not re-encode when not required
     */
    @Test
    public void testValidateMessageCorruptBase64() throws IOException, MessagingException {
        MimeMessage message = loadMessage("corrupt-base64.eml");

        /*
         * Saving the mssage used to fail with Javamail <= 1.4.3 but no longer fails with 1.4.4
         */
        message.saveChanges();

        MailUtils.validateMessage(message);

        try {
            message.getContent();

            fail();
        } catch (DecodingException e) {
            // expected
        }
    }

    @Test
    public void testValidateMessageShouldFail() throws Exception {
        MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

        MimeBodyPart emptyPart = new MimeBodyPart();

        message.setContent(emptyPart, "text/plain");

        message.saveChanges();

        try {
            MailUtils.validateMessage(message);

            fail();
        } catch (IOException e) {
            // expected. The message should be corrupt
        }
    }

    @Test
    public void testUnknownContentType() throws IOException, MessagingException {
        MimeMessage message = loadMessage("unknown-content-type.eml");

        Object content = message.getContent();

        // it seems that Javamail 1.4 returns a SharedByteArrayInputStream when
        // the message uses an unknown content type

        assertTrue(content instanceof SharedByteArrayInputStream);

        InputStream input = (SharedByteArrayInputStream) content;

        byte[] bytes = IOUtils.toByteArray(input);

        assertArrayEquals(MiscStringUtils.toAsciiBytes("body\r\n"), bytes);

        MailUtils.validateMessage(message);
    }

    @Test
    public void testUnknownContentTypeAddHeader() throws IOException, MessagingException {
        MimeMessage message = loadMessage("unknown-content-type.eml");

        message.addHeader("X-Test", "test");

        message.saveChanges();

        MailUtils.validateMessage(message);
    }

    @Test
    public void testUnknownCharsetAddHeader() throws IOException, MessagingException {
        MimeMessage message = loadMessage("unknown-charset.eml");

        message.addHeader("X-Test", "test");

        message.saveChanges();

        MailUtils.validateMessage(message);
    }

    @Test
    public void testUnknownContentTypeMultipartAddPart() throws IOException, MessagingException {
        MimeMessage message = loadMessage("unknown-content-type-multipart.eml");

        MimeMultipart multipart = (MimeMultipart) message.getContent();

        BodyPart newPart = new MimeBodyPart();
        newPart.setContent("new part", "text/plain");

        multipart.addBodyPart(newPart);

        message.saveChanges();

        MailUtils.validateMessage(message);

        File file = new File("test/tmp/testunknowncontenttypemultipartaddpart.eml");

        MailUtils.writeMessage(message, file);
    }

    @Test
    public void testConvert8BitTo7BitSimpleText() throws IOException, MessagingException {
        MimeMessage message = loadMessage("8bit-text.eml");

        assertEquals("8bIt", message.getEncoding());

        assertTrue(MailUtils.convertTo7Bit(message));

        message.saveChanges();

        assertEquals("quoted-printable", message.getEncoding());

        MailUtils.validateMessage(message);

        File file = new File("test/tmp/testConvert8BitTo7BitSimpleText.eml");

        MailUtils.writeMessage(message, file);

        assertEquals("from 8bit to quoted-printable by Djigzo", message.getHeader("X-MIME-Autoconverted", ","));
    }

    @Test
    public void testConvert8BitTo7BitBinary() throws IOException, MessagingException {
        MimeMessage message = loadMessage("8bit-binary.eml");

        assertEquals("8bit", message.getEncoding());

        assertTrue(MailUtils.convertTo7Bit(message));

        message.saveChanges();

        assertEquals("base64", message.getEncoding());

        MailUtils.validateMessage(message);

        File file = new File("test/tmp/testConvert8BitTo7BitBinary.eml");

        MailUtils.writeMessage(message, file);

        String mime = FileUtils.readFileToString(file);

        assertTrue(mime.contains("X-MIME-Autoconverted: from 8bit to base64 by Djigzo"));
        assertTrue(mime.contains("VGhpcyBpcyBhIHRlc3Qgd2l0aCB1bmxhdXRzOiBTY2jDtm4KCg=="));
    }

    @Test
    public void testConvert8BitTo7BitMultipart() throws IOException, MessagingException {
        MimeMessage message = loadMessage("8bit-multipart.eml");

        assertTrue(MailUtils.convertTo7Bit(message));

        message.saveChanges();

        MailUtils.validateMessage(message);

        File file = new File("test/tmp/testConvert8BitTo7BitMultipart.eml");

        MailUtils.writeMessage(message, file);

        String mime = FileUtils.readFileToString(file);

        assertTrue(mime.contains("X-MIME-Autoconverted: from 8bit to base64 by Djigzo"));
        assertTrue(mime.contains("X-MIME-Autoconverted: from 8bit to quoted-printable by Djigzo"));
        assertTrue(mime.contains("This is a test with unlauts: Sch=C3=B6n"));
        assertTrue(mime.contains("VGhpcyBpcyBhIHRlc3Qgd2l0aCB1bmxhdXRzOiBTY2jDtm4K"));
    }

    @Test
    public void testConvertTo7BitNoConversion() throws IOException, MessagingException {
        MimeMessage message = loadMessage("multiple-attachments.eml");

        String messageID = message.getMessageID();

        assertFalse(MailUtils.convertTo7Bit(message));

        message.saveChanges();

        MailUtils.validateMessage(message);

        // saveChanges changes the message ID so we cannot compare the result.
        // we need to set the original message id
        MimeMessageWithID mime = new MimeMessageWithID(message, messageID);

        mime.saveChanges();

        File file = new File("test/tmp/testConvertTo7BitNoConversion.eml");

        MailUtils.writeMessage(mime, file);

        // we need to correct CR/LF pairs because org only uses LF

        String result = FileUtils.readFileToString(file);

        result = StringUtils.replace(result, "\r\n", "\n").trim();

        String exp = FileUtils.readFileToString(new File(testBase, "multiple-attachments.eml"));

        exp = StringUtils.replace(exp, "\r\n", "\n").trim();

        assertEquals(exp, result);
    }
}