com.sun.mail.imap.IMAPStore Java Examples

The following examples show how to use com.sun.mail.imap.IMAPStore. 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: IMAPUtilsTest.java    From mnIMAPSync with Apache License 2.0 6 votes vote down vote up
@Test
void openStore_SSLConnection_shouldReturnIMAPSSLStore() throws Exception {
  // Given
  final IMAPSSLStore mockedStore = mock(IMAPSSLStore.class);
  doReturn(mockedStore).when(session).getStore(eq("imaps"));
  final HostDefinition hostDefinition = new HostDefinition();
  hostDefinition.setHost("mail.host");
  hostDefinition.setPort(1337);
  hostDefinition.setUser("the-user");
  hostDefinition.setPassword("the-pw");
  hostDefinition.setSsl(true);
  // When
  final IMAPStore store = openStore(hostDefinition, 1);
  // Then
  assertThat(store, equalTo(mockedStore));
  verify(store, times(1))
      .connect(eq("mail.host"), eq(1337), eq("the-user"), eq("the-pw"));
}
 
Example #2
Source File: IMAPUtilsTest.java    From mnIMAPSync with Apache License 2.0 6 votes vote down vote up
@Test
void openStore_nonSSLConnection_shouldReturnIMAPStore() throws Exception {
  // Given
  final IMAPStore mockedStore = mock(IMAPStore.class);
  doReturn(mockedStore).when(session).getStore(eq("imap"));
  final HostDefinition hostDefinition = new HostDefinition();
  hostDefinition.setHost("mail.host");
  hostDefinition.setPort(1337);
  hostDefinition.setUser("the-user");
  hostDefinition.setPassword("the-pw");
  // When
  final IMAPStore store = openStore(hostDefinition, 1);
  // Then
  assertThat(store, equalTo(mockedStore));
  verify(store, times(1))
      .connect(eq("mail.host"), eq(1337), eq("the-user"), eq("the-pw"));
}
 
Example #3
Source File: ImapServerTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testQuotaCapability() throws MessagingException {
    greenMail.setUser("foo@localhost", "pwd");
    greenMail.setQuotaSupported(false);
    final IMAPStore store = greenMail.getImap().createStore();
    try {
        store.connect("foo@localhost", "pwd");

        Quota testQuota = new Quota("INBOX");
        testQuota.setResourceLimit("STORAGE", 1024L * 42L);
        testQuota.setResourceLimit("MESSAGES", 5L);
        store.setQuota(testQuota);
        fail("Excepted MessageException since quota capability is turned off");
    } catch (MessagingException ex) {
        assertEquals(ex.getMessage(), "QUOTA not supported");
    } finally {
        store.close();
    }
}
 
Example #4
Source File: MNIMAPSync.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
private void indexTargetStore()
    throws MessagingException, GeneralSecurityException, InterruptedException {

    try (final IMAPStore targetStore = openStore(syncOptions.getTargetHost(),
        syncOptions.getThreads())) {
        populateFromStore(targetIndex, targetStore, syncOptions.getThreads());
    }
}
 
Example #5
Source File: MessageDeleterTest.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
  imapFolder = Mockito.mock(IMAPFolder.class);
  imapStore = Mockito.mock(IMAPStore.class);
  doReturn(imapFolder).when(imapStore).getFolder(anyString());
  doReturn(imapFolder).when(imapStore).getDefaultFolder();
  sourceIndex = Mockito.spy(new Index());
  sourceIndex.setFolderSeparator(".");
  targetIndex = Mockito.spy(new Index());
  targetIndex.setFolderSeparator("_");
  storeDeleter = Mockito.spy(new StoreDeleter(sourceIndex, targetIndex, imapStore, 1));
}
 
Example #6
Source File: MessageCopierTest.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
  imapFolder = Mockito.mock(IMAPFolder.class);
  doReturn('.').when(imapFolder).getSeparator();
  imapStore = Mockito.mock(IMAPStore.class);
  doReturn(imapFolder).when(imapStore).getFolder(anyString());
  doReturn(imapFolder).when(imapStore).getDefaultFolder();
  sourceIndex = Mockito.spy(new Index());
  targetIndex = Mockito.spy(new Index());
  storeCopier = Mockito.spy(new StoreCopier(imapStore, sourceIndex, imapStore, targetIndex, 1));
}
 
Example #7
Source File: StoreDeleterTest.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
  imapFolder = Mockito.mock(IMAPFolder.class);
  doReturn("MissingFolder").when(imapFolder).getFullName();
  doReturn(Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS).when(imapFolder).getType();
  doReturn(new Folder[0]).when(imapFolder).list();
  imapStore = Mockito.mock(IMAPStore.class);
  doReturn(imapFolder).when(imapStore).getFolder(anyString());
  doReturn(imapFolder).when(imapStore).getDefaultFolder();
  sourceIndex = Mockito.spy(new Index());
  sourceIndex.setFolderSeparator(".");
  targetIndex = Mockito.spy(new Index());
  targetIndex.setFolderSeparator("_");
}
 
Example #8
Source File: StoreCopierTest.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
  imapFolder = Mockito.mock(IMAPFolder.class);
  doReturn('.').doReturn('_').when(imapFolder).getSeparator();
  doReturn("INBOX").when(imapFolder).getFullName();
  doReturn(Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS).when(imapFolder).getType();
  doReturn(new Folder[0]).when(imapFolder).list();
  imapStore = Mockito.mock(IMAPStore.class);
  doReturn(imapFolder).when(imapStore).getFolder(anyString());
  doReturn(imapFolder).when(imapStore).getDefaultFolder();
  sourceIndex = Mockito.spy(new Index());
  sourceIndex.setFolderSeparator(".");
  targetIndex = Mockito.spy(new Index());
  targetIndex.setFolderSeparator("_");
}
 
Example #9
Source File: StoreCrawlerText.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
  defaultFolder = mockFolder("INBOX");
  doReturn(new IMAPFolder[]{
      mockFolder("Folder 1"), mockFolder("Folder 2")
  }).when(defaultFolder).list();
  imapStore = Mockito.mock(IMAPStore.class);
  doReturn(defaultFolder).when(imapStore).getDefaultFolder();
  doAnswer(invocation -> mockFolder(invocation.getArgument(0)))
      .when(imapStore).getFolder(anyString());
}
 
Example #10
Source File: FolderCrawlerTest.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
  imapStore = Mockito.mock(IMAPStore.class);
  folder = Mockito.mock(Folder.class);
  doReturn(folder).when(imapStore).getFolder(anyString());
  index = Mockito.spy(new Index());
}
 
Example #11
Source File: StoreCopier.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
public StoreCopier(IMAPStore sourceStore, Index sourceIndex, IMAPStore targetStore,
        Index targetIndex, int threads) {
    this.sourceStore = sourceStore;
    this.sourceIndex = sourceIndex;
    this.targetStore = targetStore;
    this.targetIndex = targetIndex;
    service = Executors.newFixedThreadPool(threads);
    foldersCopiedCount = new AtomicInteger();
    foldersSkippedCount = new AtomicInteger();
    messagesCopiedCount = new AtomicLong();
    messagesSkippedCount = new AtomicLong();
    this.copyExceptions = Collections.synchronizedList(new ArrayList<>());
}
 
Example #12
Source File: StoreDeleter.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
public StoreDeleter(Index sourceIndex, Index targetIndex, IMAPStore targetStore,
    int threads) {

    service = Executors.newFixedThreadPool(threads);
    this.targetStore = targetStore;
    this.sourceIndex = sourceIndex;
    this.targetIndex = targetIndex;
    this.foldersDeletedCount = new AtomicInteger();
    this.foldersSkippedCount = new AtomicInteger();
    this.messagesDeletedCount = new AtomicLong();
    this.messagesSkippedCount = new AtomicLong();
}
 
Example #13
Source File: MNIMAPSync.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
private void deleteFromTarget()
    throws MessagingException, GeneralSecurityException, InterruptedException {

    try (
        final IMAPStore targetStore = openStore(syncOptions.getTargetHost(),
            syncOptions.getThreads())
    ) {
        targetDeleter = new StoreDeleter(sourceIndex, targetIndex, targetStore,
            syncOptions.getThreads());
        targetDeleter.delete();
    }
}
 
Example #14
Source File: MNIMAPSync.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
private void copySourceToTarget()
    throws MessagingException, GeneralSecurityException, InterruptedException {

    try (
        final IMAPStore targetStore = openStore(syncOptions.getTargetHost(),
            syncOptions.getThreads());
        final IMAPStore sourceStore = openStore(syncOptions.getSourceHost(),
            syncOptions.getThreads())
    ) {
        sourceCopier = new StoreCopier(sourceStore, sourceIndex, targetStore, targetIndex,
            syncOptions.getThreads());
        sourceCopier.copy();
    }
}
 
Example #15
Source File: Core.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private static void reportEmptyMessage(Context context, State state, EntityAccount account, IMAPStore istore) {
    try {
        if (istore.hasCapability("ID")) {
            Map<String, String> id = new LinkedHashMap<>();
            id.put("name", context.getString(R.string.app_name));
            id.put("version", BuildConfig.VERSION_NAME);
            Map<String, String> sid = istore.id(id);
            if (sid != null) {
                StringBuilder sb = new StringBuilder();
                for (String key : sid.keySet())
                    sb.append(" ").append(key).append("=").append(sid.get(key));
                if (!account.partial_fetch)
                    Log.e("Empty message" + sb.toString());
            }
        } else {
            if (!account.partial_fetch)
                Log.e("Empty message " + account.host);
        }
    } catch (Throwable ex) {
        Log.w(ex);
    }

    // Auto disable partial fetch
    if (account.partial_fetch) {
        account.partial_fetch = false;
        DB db = DB.getInstance(context);
        db.account().setAccountPartialFetch(account.id, account.partial_fetch);
        state.error(new StoreClosedException(istore));
    }
}
 
Example #16
Source File: EmailService.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
boolean hasCapability(String capability) throws MessagingException {
    Store store = getStore();
    if (store instanceof IMAPStore)
        return ((IMAPStore) getStore()).hasCapability(capability);
    else
        return false;
}
 
Example #17
Source File: MailNotificationService.java    From camunda-bpm-mail with Apache License 2.0 5 votes vote down vote up
protected boolean supportsIdle(Folder folder) throws MessagingException {
	Store store = folder.getStore();

	if (store instanceof IMAPStore) {
		IMAPStore imapStore = (IMAPStore) store;
		return imapStore.hasCapability("IDLE") && folder instanceof IMAPFolder;
	} else {
		return false;
	}
}
 
Example #18
Source File: ImapServerTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testFolderRequiringEscaping() throws MessagingException {
    greenMail.setUser("foo@localhost", "pwd");
    GreenMailUtil.sendTextEmail("foo@localhost", "foo@localhost", "test subject", "", greenMail.getSmtp().getServerSetup());

    final IMAPStore store = greenMail.getImap().createStore();
    store.connect("foo@localhost", "pwd");
    try {

        // Create some folders
        Folder inboxFolder = store.getFolder("INBOX");
        inboxFolder.open(Folder.READ_ONLY);

        final Folder folderRequiringEscaping = inboxFolder.getFolder("requires escaping Ä");
        assertTrue(folderRequiringEscaping.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES));
        folderRequiringEscaping.open(Folder.READ_WRITE);

        assertEquals(0, folderRequiringEscaping.getMessageCount());
        assertEquals(1, inboxFolder.getMessageCount());

        inboxFolder.copyMessages(inboxFolder.getMessages(), folderRequiringEscaping);

        folderRequiringEscaping.expunge(); // invalidates folder cache
        assertEquals(1, folderRequiringEscaping.getMessageCount());
    } finally {
        store.close();
    }
}
 
Example #19
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = MockTestException.class)
public void testQUOTAUnsupported() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore("mock_imap");
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final Folder test = defaultFolder.getFolder("test");

    final IMAPStore imapStore = (IMAPStore) store;

    try {
        imapStore.getQuota("");
    } catch (final MessagingException e) {
        throw new MockTestException(e);
    }

}
 
Example #20
Source File: ImapServerTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * https://tools.ietf.org/html/rfc3501#page-37 :
 * <q>
 *     Renaming INBOX is permitted, and has special behavior.  It moves
 *     all messages in INBOX to a new mailbox with the given name,
 *     leaving INBOX empty.  If the server implementation supports
 *     inferior hierarchical names of INBOX, these are unaffected by a
 *     rename of INBOX.
 *  </q>
 *
 * @throws MessagingException
 */
@Test
public void testRenameINBOXFolder() throws MessagingException {
    greenMail.setUser("foo@localhost", "pwd");
    GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test subject",
            "Test message", greenMail.getSmtp().getServerSetup());

    final IMAPStore store = greenMail.getImap().createStore();
    store.connect("foo@localhost", "pwd");
    try {

        // Create some folders
        Folder inboxFolder = store.getFolder("INBOX");
        assertTrue(inboxFolder.exists());
        inboxFolder.open(Folder.READ_ONLY);
        assertEquals(1, inboxFolder.getMessages().length);

        Folder inboxRenamedFolder = store.getFolder("INBOX-renamed");
        assertFalse(inboxRenamedFolder.exists());

        inboxFolder.close(true);
        inboxFolder.renameTo(inboxRenamedFolder);
        assertTrue(inboxRenamedFolder.exists());
        inboxRenamedFolder.open(Folder.READ_ONLY);
        assertEquals(1, inboxRenamedFolder.getMessages().length);

        inboxFolder = store.getFolder("INBOX");
        assertTrue(inboxFolder.exists());
        inboxFolder.open(Folder.READ_ONLY);
        assertEquals(0, inboxFolder.getMessages().length);
    } finally {
        store.close();
    }
}
 
Example #21
Source File: ExampleJavaMailTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendAndReceive() throws UnsupportedEncodingException, MessagingException, UserException {
    Session smtpSession = greenMail.getSmtp().createSession();

    Message msg = new MimeMessage(smtpSession);
    msg.setFrom(new InternetAddress("[email protected]"));
    msg.addRecipient(Message.RecipientType.TO,
            new InternetAddress("[email protected]"));
    msg.setSubject("Email sent to GreenMail via plain JavaMail");
    msg.setText("Fetch me via IMAP");
    Transport.send(msg);

    // Create user, as connect verifies pwd
    greenMail.setUser("[email protected]", "[email protected]", "secret-pwd");

    // Alternative 1: Create session and store or ...
    Session imapSession = greenMail.getImap().createSession();
    Store store = imapSession.getStore("imap");
    store.connect("[email protected]", "secret-pwd");
    Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Message msgReceived = inbox.getMessage(1);
    assertEquals(msg.getSubject(), msgReceived.getSubject());

    // Alternative 2: ... let GreenMail create and configure a store:
    IMAPStore imapStore = greenMail.getImap().createStore();
    imapStore.connect("[email protected]", "secret-pwd");
    inbox = imapStore.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    msgReceived = inbox.getMessage(1);
    assertEquals(msg.getSubject(), msgReceived.getSubject());

    // Alternative 3: ... directly fetch sent message using GreenMail API
    assertEquals(1, greenMail.getReceivedMessagesForDomain("[email protected]").length);
    msgReceived = greenMail.getReceivedMessagesForDomain("[email protected]")[0];
    assertEquals(msg.getSubject(), msgReceived.getSubject());

    store.close();
    imapStore.close();
}
 
Example #22
Source File: ImapServerTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpunge() throws MessagingException {
    greenMail.setUser("foo@localhost", "pwd");

    for (int i = 0; i < 6; i++) {
        GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test subject #" + i,
                "Test message", ServerSetupTest.SMTP);
    }
    final IMAPStore store = greenMail.getImap().createStore();
    store.connect("foo@localhost", "pwd");
    try {
        Folder inboxFolder = store.getFolder("INBOX");
        inboxFolder.open(Folder.READ_WRITE);

        Message[] messages = inboxFolder.getMessages();
        assertEquals(6, messages.length);
        inboxFolder.setFlags(new int[]{2, 3}, new Flags(DELETED), true); // 1 and 2, offset is not zero-based

        assertFalse(inboxFolder.getMessage(1).isSet(DELETED));
        assertTrue(inboxFolder.getMessage(2).isSet(DELETED));
        assertTrue(inboxFolder.getMessage(3).isSet(DELETED));
        assertFalse(inboxFolder.getMessage(4).isSet(DELETED));
        assertFalse(inboxFolder.getMessage(5).isSet(DELETED));
        assertFalse(inboxFolder.getMessage(6).isSet(DELETED));
        assertEquals(2, inboxFolder.getDeletedMessageCount());
        Message[] expunged = inboxFolder.expunge();
        assertEquals(2, expunged.length);

        messages = inboxFolder.getMessages();
        assertEquals(4, messages.length);
        assertEquals("Test subject #0", messages[0].getSubject());
        assertEquals("Test subject #3", messages[1].getSubject());
        assertEquals("Test subject #4", messages[2].getSubject());
        assertEquals("Test subject #5", messages[3].getSubject());
    } finally {
        store.close();
    }
}
 
Example #23
Source File: SenderRecipientTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendAndReceiveWithQuotedAddress() throws MessagingException, IOException {
    // See https://en.wikipedia.org/wiki/Email_address#Local-part
    String[] toList = {"\"John..Doe\"@localhost",
            "abc.\"defghi\".xyz@localhost",
            "\"abcdefghixyz\"@localhost",
            "\"Foo Bar\"admin@localhost"
    };
    for(String to: toList) {
        greenMail.setUser(to, "pwd");
        InternetAddress[] toAddress = InternetAddress.parse(to);
        String from = to; // Same from and to address for testing correct escaping of both

        final String subject = "testSendAndReceiveWithQuotedAddress";
        final String content = "some body";
        GreenMailUtil.sendTextEmailTest(to, from,
                subject, content);

        assertTrue(greenMail.waitForIncomingEmail(5000, 1));

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect(to, "pwd");
        try {
            IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            Message[] msgs = folder.getMessages();
            assertTrue(null != msgs && msgs.length == 1);
            final Message msg = msgs[0];
            assertEquals(to, ((InternetAddress)msg.getRecipients(Message.RecipientType.TO)[0]).getAddress());
            assertEquals(from, ((InternetAddress)msg.getFrom()[0]).getAddress());
            assertEquals(subject, msg.getSubject());
            assertEquals(content, msg.getContent().toString());
            assertArrayEquals(toAddress, msg.getRecipients(Message.RecipientType.TO));
        } finally {
            store.close();
        }
    }
}
 
Example #24
Source File: StoreCopier.java    From mnIMAPSync with Apache License 2.0 4 votes vote down vote up
final IMAPStore getTargetStore() {
    return targetStore;
}
 
Example #25
Source File: ImapServer.java    From greenmail with Apache License 2.0 4 votes vote down vote up
@Override
public IMAPStore createStore() throws NoSuchProviderException {
    return (IMAPStore) super.createStore();
}
 
Example #26
Source File: Rfc822MessageTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
/**
 * Structure of test message and content type:
 * <p>
 * Message (multipart/mixed)
 * \--> MultiPart (multipart/mixed)
 * \--> MimeBodyPart (message/rfc822)
 * \--> Message (text/plain)
 */
@Test
public void testForwardWithRfc822() throws MessagingException, IOException {
    greenMail.setUser("foo@localhost", "pwd");
    final Session session = greenMail.getSmtp().createSession();

    // Message for forwarding
    Message msgToBeForwarded = GreenMailUtil.createTextEmail(
            "foo@localhost", "foo@localhost", "test newMessageWithForward", "forwarded mail content",
            greenMail.getSmtp().getServerSetup());


    // Create body part containing forwarded message
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(msgToBeForwarded, "message/rfc822");

    // Add message body part to multi part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // New main message, containing body part
    MimeMessage newMessageWithForward = new MimeMessage(session);
    newMessageWithForward.setRecipient(Message.RecipientType.TO, new InternetAddress("foo@localhost"));
    newMessageWithForward.setSubject("Fwd: " + "test");
    newMessageWithForward.setFrom(new InternetAddress("foo@localhost"));
    newMessageWithForward.setContent(multipart);   //Save changes in newMessageWithForward message
    newMessageWithForward.saveChanges();

    GreenMailUtil.sendMimeMessage(newMessageWithForward);

    final IMAPStore store = greenMail.getImap().createStore();
    store.connect("foo@localhost", "pwd");
    try {
        Folder inboxFolder = store.getFolder("INBOX");
        inboxFolder.open(Folder.READ_WRITE);
        Message[] messages = inboxFolder.getMessages();
        MimeMessage msg = (MimeMessage) messages[0];
        assertTrue(msg.getContentType().startsWith("multipart/mixed"));
        Multipart multipartReceived = (Multipart) msg.getContent();
        assertTrue(multipartReceived.getContentType().startsWith("multipart/mixed"));
        MimeBodyPart mimeBodyPartReceived = (MimeBodyPart) multipartReceived.getBodyPart(0);
        assertTrue(mimeBodyPartReceived.getContentType().toLowerCase().startsWith("message/rfc822"));

        MimeMessage msgAttached = (MimeMessage) mimeBodyPartReceived.getContent();
        assertThat(msgAttached.getContentType().toLowerCase(), startsWith("text/plain"));
        assertArrayEquals(msgToBeForwarded.getRecipients(Message.RecipientType.TO), msgAttached.getRecipients(Message.RecipientType.TO));
        assertArrayEquals(msgToBeForwarded.getFrom(), msgAttached.getFrom());
        assertEquals(msgToBeForwarded.getSubject(), msgAttached.getSubject());
        assertEquals(msgToBeForwarded.getContent(), msgAttached.getContent());
    } finally {
        store.close();
    }
}
 
Example #27
Source File: EncodingTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
/**
 * Structure of test message and content type:
 * <p>
 * Message (multipart/alternative)
 * \--> Message (text/plain)
 */
@Test
public void testTextPlainWithUTF8() throws MessagingException, IOException {
    greenMail.setUser("foo@localhost", "pwd");
    final Session session = greenMail.getSmtp().createSession();

    MimeMultipart multipart = new MimeMultipart("alternative");

    MimeBodyPart textQP = new MimeBodyPart();
    textQP.setContent("QP Content with umlaut \u00FC", "text/javascript; charset=utf-8");
    textQP.setHeader("Content-Transfer-Encoding", "QUOTED-PRINTABLE");
    multipart.addBodyPart(textQP);

    MimeBodyPart html = new MimeBodyPart();
    html.setContent(MimeUtility.encodeText("<!doctype html>" +
            "<html lang=en>" +
            "<head>" +
            "<meta charset=utf-8>" +
            "<title>Title with Umlaut \u00FC</title>" +
            "</head>" +
            "<body>" +
            "<p>8BIT Content with umlaut ü</p>" +
            "</body>" +
            "</html>", "UTF-8", "B"), "text/html; charset=utf-8");
    html.setHeader("Content-Transfer-Encoding", "8BIT");
    multipart.addBodyPart(html);

    MimeBodyPart text = new MimeBodyPart();
    text.setText(MimeUtility.encodeText("8BIT Content with umlaut \u00FC", "UTF-8", "B"), "utf-8");
    text.setHeader("Content-Transfer-Encoding", "8BIT");
    multipart.addBodyPart(text);

    MimeBodyPart text2QP = new MimeBodyPart();
    text2QP.setText(MimeUtility.encodeText("8BIT Content with umlaut \u00FC", "UTF-8", "Q"), "utf-8");
    text2QP.setHeader("Content-Transfer-Encoding", "8BIT");
    multipart.addBodyPart(text2QP);


    // New main message, containing body part
    MimeMessage message = new MimeMessage(session);
    message.setRecipient(Message.RecipientType.TO, new InternetAddress("foo@localhost"));
    message.setSubject("Subject ä", "UTF-8");
    message.setFrom(new InternetAddress("foo@localhost"));
    message.setContent(multipart);
    message.saveChanges();

    GreenMailUtil.sendMimeMessage(message);

    final IMAPStore store = greenMail.getImap().createStore();
    store.connect("foo@localhost", "pwd");
    try {
        Folder inboxFolder = store.getFolder("INBOX");
        inboxFolder.open(Folder.READ_WRITE);
        Message[] messages = inboxFolder.getMessages();
        MimeMessage msg = (MimeMessage) messages[0];
        message.writeTo(new FileOutputStream(new File("t.eml")));
        assertTrue(msg.getContentType().startsWith("multipart/alternative"));
        Multipart multipartReceived = (Multipart) msg.getContent();

        assertTrue(multipartReceived.getContentType().startsWith("multipart/alternative"));

        // QP-encoded
        final BodyPart bodyPart0 = multipartReceived.getBodyPart(0);
        assertEquals("TEXT/JAVASCRIPT; charset=utf-8", bodyPart0.getContentType());
        assertEquals(textQP.getContent(), EncodingUtil.toString((InputStream) bodyPart0.getContent(), StandardCharsets.UTF_8));

        // 8-BIT-encoded
        final BodyPart bodyPart1 = multipartReceived.getBodyPart(1);
        assertEquals("TEXT/HTML; charset=utf-8", bodyPart1.getContentType());
        assertEquals(html.getContent(), bodyPart1.getContent()); // Fails

        final BodyPart bodyPart2 = multipartReceived.getBodyPart(2);
        assertEquals("TEXT/PLAIN; charset=utf-8", bodyPart2.getContentType());
        assertEquals(text.getContent(), bodyPart2.getContent());

        final BodyPart bodyPart3 = multipartReceived.getBodyPart(3);
        assertEquals("TEXT/PLAIN; charset=utf-8", bodyPart3.getContentType());
        assertEquals(text2QP.getContent(), bodyPart3.getContent());
    } finally {
        store.close();
    }
}
 
Example #28
Source File: StoreCopier.java    From mnIMAPSync with Apache License 2.0 4 votes vote down vote up
final IMAPStore getSourceStore() {
    return sourceStore;
}
 
Example #29
Source File: StoreDeleter.java    From mnIMAPSync with Apache License 2.0 4 votes vote down vote up
final IMAPStore getTargetStore() {
    return targetStore;
}
 
Example #30
Source File: ImapServerTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
@Test
public void testRenameFolder() throws MessagingException {
    greenMail.setUser("foo@localhost", "pwd");

    final IMAPStore store = greenMail.getImap().createStore();
    store.connect("foo@localhost", "pwd");
    try {

        // Create some folders
        Folder inboxFolder = store.getFolder("INBOX");
        Folder newFolder = inboxFolder.getFolder("foo-folder");
        assertTrue(newFolder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES));
        assertTrue(newFolder.exists());

        Folder renamedFolder = inboxFolder.getFolder("foo-folder-renamed");
        assertFalse(renamedFolder.exists());

        // Rename
        assertTrue(newFolder.renameTo(renamedFolder));
        assertFalse(newFolder.exists());
        assertTrue(renamedFolder.exists());

        // Rename with sub folder
        Folder subFolder = renamedFolder.getFolder("bar");
        assertTrue(subFolder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES));
        assertTrue(subFolder.exists());

        Folder renamedFolder2 = inboxFolder.getFolder("foo-folder-renamed-again");
        assertTrue(renamedFolder.renameTo(renamedFolder2));
        assertFalse(renamedFolder.exists());
        assertTrue(renamedFolder2.exists());
        assertTrue(renamedFolder2.getFolder("bar").exists()); // check that sub folder still exists

        // Rename to a different parent folder
        // INBOX.foo-folder-renamed-again -> INBOX.foo2.foo3
        Folder foo2Folder = inboxFolder.getFolder("foo2");
        assertTrue(foo2Folder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES));
        assertTrue(foo2Folder.exists());
        Folder foo3Folder = foo2Folder.getFolder("foo3");
        assertFalse(foo3Folder.exists());

        renamedFolder2.renameTo(foo3Folder);
        assertTrue(inboxFolder.getFolder("foo2.foo3").exists());
        assertFalse(inboxFolder.getFolder("foo-folder-renamed-again").exists());
    } finally {
        store.close();
    }
}