Java Code Examples for com.sun.mail.imap.IMAPFolder

The following examples show how to use com.sun.mail.imap.IMAPFolder. 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
Source Project: FairEmail   Source File: Core.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void onSeen(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, JSONException {
    // Mark message (un)seen
    DB db = DB.getInstance(context);

    if (!ifolder.getPermanentFlags().contains(Flags.Flag.SEEN)) {
        db.message().setMessageSeen(message.id, false);
        db.message().setMessageUiSeen(message.id, false);
        return;
    }

    boolean seen = jargs.getBoolean(0);
    if (message.seen.equals(seen))
        return;

    Message imessage = ifolder.getMessageByUID(message.uid);
    if (imessage == null)
        throw new MessageRemovedException();

    imessage.setFlag(Flags.Flag.SEEN, seen);

    db.message().setMessageSeen(message.id, seen);
}
 
Example 2
Source Project: FairEmail   Source File: Core.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void onFlag(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, JSONException {
    // Star/unstar message
    DB db = DB.getInstance(context);

    if (!ifolder.getPermanentFlags().contains(Flags.Flag.FLAGGED)) {
        db.message().setMessageFlagged(message.id, false);
        db.message().setMessageUiFlagged(message.id, false, null);
        return;
    }

    boolean flagged = jargs.getBoolean(0);
    if (message.flagged.equals(flagged))
        return;

    Message imessage = ifolder.getMessageByUID(message.uid);
    if (imessage == null)
        throw new MessageRemovedException();

    imessage.setFlag(Flags.Flag.FLAGGED, flagged);

    db.message().setMessageFlagged(message.id, flagged);
}
 
Example 3
Source Project: FairEmail   Source File: Core.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void onAnswered(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, JSONException {
    // Mark message (un)answered
    DB db = DB.getInstance(context);

    if (!ifolder.getPermanentFlags().contains(Flags.Flag.ANSWERED)) {
        db.message().setMessageAnswered(message.id, false);
        db.message().setMessageUiAnswered(message.id, false);
        return;
    }

    boolean answered = jargs.getBoolean(0);
    if (message.answered.equals(answered))
        return;

    // This will be fixed when moving the message
    if (message.uid == null)
        return;

    Message imessage = ifolder.getMessageByUID(message.uid);
    if (imessage == null)
        throw new MessageRemovedException();

    imessage.setFlag(Flags.Flag.ANSWERED, answered);

    db.message().setMessageAnswered(message.id, answered);
}
 
Example 4
Source Project: FairEmail   Source File: Core.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void onKeyword(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, JSONException {
    // Set/reset user flag
    DB db = DB.getInstance(context);
    // https://tools.ietf.org/html/rfc3501#section-2.3.2
    String keyword = jargs.getString(0);
    boolean set = jargs.getBoolean(1);

    if (TextUtils.isEmpty(keyword))
        throw new IllegalArgumentException("keyword/empty");

    if (!ifolder.getPermanentFlags().contains(Flags.Flag.USER)) {
        db.message().setMessageKeywords(message.id, DB.Converters.fromStringArray(null));
        return;
    }

    if (message.uid == null)
        throw new IllegalArgumentException("keyword/uid");

    Message imessage = ifolder.getMessageByUID(message.uid);
    if (imessage == null)
        throw new MessageRemovedException();

    Flags flags = new Flags(keyword);
    imessage.setFlags(flags, set);
}
 
Example 5
Source Project: FairEmail   Source File: Core.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void onBody(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, IOException {
    // Download message body
    DB db = DB.getInstance(context);

    if (message.content)
        return;

    // Get message
    Message imessage = ifolder.getMessageByUID(message.uid);
    if (imessage == null)
        throw new MessageRemovedException();

    MessageHelper helper = new MessageHelper((MimeMessage) imessage, context);
    MessageHelper.MessageParts parts = helper.getMessageParts();
    String body = parts.getHtml(context);
    File file = message.getFile(context);
    Helper.writeText(file, body);
    db.message().setMessageContent(message.id,
            true,
            HtmlHelper.getLanguage(context, body),
            parts.isPlainOnly(),
            HtmlHelper.getPreview(body),
            parts.getWarnings(message.warning));
}
 
Example 6
private static RFC822DATA getRFC822Message(final IMAPFolder folder, final long uid) throws MessagingException
{
    return (RFC822DATA) folder.doCommand(new IMAPFolder.ProtocolCommand()
    {
        public Object doCommand(IMAPProtocol p) throws ProtocolException
        {
            Response[] r = p.command("UID FETCH " + uid + " (RFC822)", null);
            logResponse(r);
            Response response = r[r.length - 1];
            if (!response.isOK())
            {
                throw new ProtocolException("Unable to retrieve message in RFC822 format");
            }

            FetchResponse fetchResponse = (FetchResponse) r[0];
            return fetchResponse.getItem(RFC822DATA.class);
        }
    });
   
}
 
Example 7
/**
 * Returns BODY object containing desired message fragment
 * 
 * @param folder Folder containing the message
 * @param uid Message UID
 * @param from starting byte
 * @param count bytes to read
 * @return BODY containing desired message fragment
 * @throws MessagingException
 */
private static BODY getMessageBodyPart(IMAPFolder folder, final Long uid, final Integer from, final Integer count) throws MessagingException
{
    return (BODY) folder.doCommand(new IMAPFolder.ProtocolCommand()
    {
        public Object doCommand(IMAPProtocol p) throws ProtocolException
        {
            Response[] r = p.command("UID FETCH " + uid + " (FLAGS BODY.PEEK[]<" + from + "." + count + ">)", null);
            logResponse(r);
            Response response = r[r.length - 1];

            // Grab response
            if (!response.isOK())
            {
                throw new ProtocolException("Unable to retrieve message part <" + from + "." + count + ">");
            }

            FetchResponse fetchResponse = (FetchResponse) r[0];
            BODY body = (BODY) fetchResponse.getItem(com.sun.mail.imap.protocol.BODY.class);
            return body;
        }
    });

}
 
Example 8
/**
 * Returns a full message body
 * 
 * @param folder Folder containing the message
 * @param uid Message UID
 * @return Returns size of the message
 * @throws MessagingException
 */
private static BODY getMessageBody(IMAPFolder folder, final Long uid) throws MessagingException
{
    return (BODY) folder.doCommand(new IMAPFolder.ProtocolCommand()
    {
        public Object doCommand(IMAPProtocol p) throws ProtocolException
        {
            Response[] r = p.command("UID FETCH " + uid + " (FLAGS BODY.PEEK[])", null);
            logResponse(r);
            Response response = r[r.length - 1];

            // Grab response
            if (!response.isOK())
            {
                throw new ProtocolException("Unable to retrieve message size");
            }
            FetchResponse fetchResponse = (FetchResponse) r[0];
            BODY body = (BODY) fetchResponse.getItem(BODY.class);
            return body;
        }
    });
}
 
Example 9
Source Project: camunda-bpm-mail   Source File: IdleNotificationWorker.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void stop() {
  runnning = false;

  // perform a NOOP to interrupt IDLE
  try {
    folder.doCommand(new IMAPFolder.ProtocolCommand() {
      public Object doCommand(IMAPProtocol p) throws ProtocolException {
            p.simpleCommand("NOOP", null);
            return null;
        }
    });
  } catch (MessagingException e) {
    // ignore
  }
}
 
Example 10
Source Project: camunda-bpm-mail   Source File: MailNotificationService.java    License: Apache License 2.0 6 votes vote down vote up
public void start(String folderName) throws Exception {
	executorService = Executors.newSingleThreadExecutor();

	Folder folder = mailService.ensureOpenFolder(folderName);

	folder.addMessageCountListener(new MessageCountAdapter() {
		@Override
		public void messagesAdded(MessageCountEvent event) {
			List<Message> messages = Arrays.asList(event.getMessages());

			handlers.forEach(handler -> handler.accept(messages));
		}
	});

	if (supportsIdle(folder)) {
		notificationWorker = new IdleNotificationWorker(mailService, (IMAPFolder) folder);
	} else {
		notificationWorker = new PollNotificationWorker(mailService, folder,
				configuration.getNotificationLookupTime());
	}

	LOGGER.debug("start notification service: {}", notificationWorker);

	executorService.submit(notificationWorker);
}
 
Example 11
Source Project: Ardulink-1   Source File: MailListener.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MessagingException {
	initConfiguration();
	initInbox();
	System.out.println("Messages in inbox: " + inbox.getMessageCount());
	
	// Add messageCountListener to listen for new messages
	inbox.addMessageCountListener(new ArdulinkMailMessageCountAdapter());
	
	// TODO pezzo da rivedere. Perch� casto a IMAP se l'ho messo in configurazione? Perch�
	// casto ad una classe proprietaria della SUN?
	// NON esiste codice pi� standard?
	// Se ho un listener non posso semplicemente ciclare questo thread con una sleep?
	// int freq = 1000;
	while(true) {
		IMAPFolder f = (IMAPFolder)inbox;
		f.idle();
		System.out.println("IDLE done");
	}
}
 
Example 12
Source Project: javamail-mock2   Source File: Main.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {

    while (!Thread.interrupted()) {
        try {
            // System.out.println("enter idle");
            ((IMAPFolder) folder).idle();
            idleCount++;
            // System.out.println("leave idle");
            Thread.sleep(500);
        } catch (final Exception e) {
            exception = e;
        }
    }

    // System.out.println("leave run()");
}
 
Example 13
Source Project: javamail-mock2   Source File: IMAPTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {

    while (!Thread.interrupted()) {
        try {
            // System.out.println("enter idle");
            ((IMAPFolder) folder).idle();
            idleCount++;
            // System.out.println("leave idle");
        } catch (final Exception e) {
            exception = e;
        }
    }

    // System.out.println("leave run()");
}
 
Example 14
Source Project: greenmail   Source File: ImapProtocolTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testListAndStatusWithNonExistingFolder() throws MessagingException {
    store.connect("[email protected]", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        assertFalse(folder.getFolder("non existent folder").exists());
        for (final String cmd : new String[]{
                "STATUS \"non existent folder\" (MESSAGES UIDNEXT UIDVALIDITY UNSEEN)",
                "SELECT \"non existent folder\""
        }) {
            Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
                @Override
                public Object doCommand(IMAPProtocol protocol) {
                    return protocol.command(cmd, null);
                }
            });

            IMAPResponse response = (IMAPResponse) ret[0];
            assertTrue(response.isNO());
        }
    } finally {
        store.close();
    }
}
 
Example 15
Source Project: greenmail   Source File: ImapProtocolTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSearchNotFlags() throws MessagingException {
    store.connect("[email protected]", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);
        folder.setFlags(new int[]{2, 3}, new Flags(Flags.Flag.ANSWERED), true);
        Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("SEARCH NOT (ANSWERED) NOT (DELETED) NOT (SEEN) NOT (FLAGGED) ALL", null);
            }
        });
        IMAPResponse response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals("1 4 5 6 7 8 9 10" /* 2 and 3 set to answered */, response.getRest());
    } finally {
        store.close();
    }
}
 
Example 16
Source Project: greenmail   Source File: ImapProtocolTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetMessageByUnknownUidInEmptyINBOX() throws MessagingException, FolderException {
    greenMail.getManagers()
            .getImapHostManager()
            .getInbox(user)
            .deleteAllMessages();
    store.connect("[email protected]", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        Message message = folder.getMessageByUID(666);
        assertNull(message);
    } finally {
        store.close();
    }
}
 
Example 17
Source Project: ImapNote2   Source File: SyncUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void GetNotes(Account account, Folder notesFolder, Context ctx, NotesDb storedNotes) throws MessagingException, IOException{
  Long UIDM;
  Message notesMessage;
  File directory = new File (ctx.getFilesDir() + "/" + account.name);
  if (notesFolder.isOpen()) {
    if ((notesFolder.getMode() & Folder.READ_ONLY) != 0)
      notesFolder.open(Folder.READ_ONLY);
  } else {
    notesFolder.open(Folder.READ_ONLY);
  }
  UIDValidity = GetUIDValidity(account, ctx);
  SetUIDValidity(account, UIDValidity, ctx);
  Message[] notesMessages = notesFolder.getMessages();
  //Log.d(TAG,"number of messages in folder="+(notesMessages.length));
  for(int index=notesMessages.length-1; index>=0; index--) {
      notesMessage = notesMessages[index];
      // write every message in files/{accountname} directory
      // filename is the original message uid
      UIDM=((IMAPFolder)notesFolder).getUID(notesMessage);
      String suid = UIDM.toString();
      File outfile = new File (directory, suid);
      GetOneNote(outfile, notesMessage, storedNotes, account.name, suid, true);
  }
}
 
Example 18
Source Project: mnIMAPSync   Source File: MessageId.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * Adds required headers to fetch profile
     */
    public static FetchProfile addHeaders(FetchProfile fetchProfile) {
        fetchProfile.add(FetchProfile.Item.ENVELOPE);
        //Some servers respond to get a header request with a partial response of the header
        //when hMailServer is fetched for To or From, it returns only the first entry,
        //so when compared with other server versions, e-mails appear to be different.
        fetchProfile.add(IMAPFolder.FetchProfileItem.HEADERS);
        //If using the header consructor add this for performance.
//        for (String header : new String[]{
//            MessageId.HEADER_MESSAGE_ID,
//            MessageId.HEADER_SUBJECT,
//            MessageId.HEADER_FROM,
//            MessageId.HEADER_TO}) {
//            fetchProfile.add(header.toUpperCase());
//        }
        return fetchProfile;
    }
 
Example 19
Source Project: FairEmail   Source File: Core.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void onHeaders(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException {
    // Download headers
    DB db = DB.getInstance(context);

    if (message.headers != null)
        return;

    IMAPMessage imessage = (IMAPMessage) ifolder.getMessageByUID(message.uid);
    if (imessage == null)
        throw new MessageRemovedException();

    MessageHelper helper = new MessageHelper(imessage, context);
    db.message().setMessageHeaders(message.id, helper.getHeaders());
}
 
Example 20
Source Project: FairEmail   Source File: Core.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void onRaw(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, IOException, JSONException {
    // Download raw message
    DB db = DB.getInstance(context);

    if (message.raw == null || !message.raw) {
        IMAPMessage imessage = (IMAPMessage) ifolder.getMessageByUID(message.uid);
        if (imessage == null)
            throw new MessageRemovedException();

        File file = message.getRawFile(context);
        try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
            imessage.writeTo(os);
        }

        db.message().setMessageRaw(message.id, true);
    }

    if (jargs.length() > 0) {
        // Cross account move
        long tid = jargs.getLong(0);
        EntityFolder target = db.folder().getFolder(tid);
        if (target == null)
            throw new FolderNotFoundException();

        Log.i(folder.name + " queuing ADD id=" + message.id + ":" + target.id);

        EntityOperation operation = new EntityOperation();
        operation.account = target.account;
        operation.folder = target.id;
        operation.message = message.id;
        operation.name = EntityOperation.ADD;
        operation.args = jargs.toString();
        operation.created = new Date().getTime();
        operation.id = db.operation().insertOperation(operation);
    }
}
 
Example 21
Source Project: FairEmail   Source File: Core.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void onAttachment(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, EntityOperation op, IMAPFolder ifolder) throws JSONException, MessagingException, IOException {
    // Download attachment
    DB db = DB.getInstance(context);

    long id = jargs.getLong(0);

    // Get attachment
    EntityAttachment attachment = db.attachment().getAttachment(id);
    if (attachment == null)
        attachment = db.attachment().getAttachment(message.id, (int) id); // legacy
    if (attachment == null)
        throw new IllegalArgumentException("Local attachment not found");
    if (attachment.available)
        return;

    // Get message
    Message imessage = ifolder.getMessageByUID(message.uid);
    if (imessage == null)
        throw new MessageRemovedException();

    // Get message parts
    MessageHelper helper = new MessageHelper((MimeMessage) imessage, context);
    MessageHelper.MessageParts parts = helper.getMessageParts();

    // Download attachment
    parts.downloadAttachment(context, attachment);
}
 
Example 22
Source Project: FairEmail   Source File: Core.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void onSubscribeFolder(Context context, JSONArray jargs, EntityFolder folder, IMAPFolder ifolder)
        throws JSONException, MessagingException {
    boolean subscribe = jargs.getBoolean(0);
    ifolder.setSubscribed(subscribe);

    DB db = DB.getInstance(context);
    db.folder().setFolderSubscribed(folder.id, subscribe);

    Log.i(folder.name + " subscribed=" + subscribe);
}
 
Example 23
Source Project: FairEmail   Source File: EmailService.java    License: GNU General Public License v3.0 5 votes vote down vote up
List<EntityFolder> getFolders() throws MessagingException {
    List<EntityFolder> folders = new ArrayList<>();

    for (Folder ifolder : getStore().getDefaultFolder().list("*")) {
        String fullName = ifolder.getFullName();
        String[] attrs = ((IMAPFolder) ifolder).getAttributes();
        String type = EntityFolder.getType(attrs, fullName, true);
        Log.i(fullName + " attrs=" + TextUtils.join(" ", attrs) + " type=" + type);

        if (type != null)
            folders.add(new EntityFolder(fullName, type));
    }

    EntityFolder.guessTypes(folders, getStore().getDefaultFolder().getSeparator());

    boolean inbox = false;
    boolean drafts = false;
    for (EntityFolder folder : folders)
        if (EntityFolder.INBOX.equals(folder.type))
            inbox = true;
        else if (EntityFolder.DRAFTS.equals(folder.type))
            drafts = true;

    if (!inbox || !drafts)
        return null;

    return folders;
}
 
Example 24
Source Project: camunda-bpm-mail   Source File: MailNotificationService.java    License: 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 25
/**
 * Remove not needed elements
 */
private static Message[] removeAlreadyImported(IMAPFolder folder, Message[] messages, long startUid) throws MessagingException {
	List<Message> result = new LinkedList<>();

	for (Message msg : messages) {
		long msgUid = folder.getUID(msg);

		if (msgUid >= startUid) {
			result.add(msg);
		}
	}

	return result.toArray(new Message[0]);
}
 
Example 26
Source Project: javamail-mock2   Source File: IMAPTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = MockTestException.class)
public void testACLUnsupported() 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 IMAPFolder testImap = (IMAPFolder) test;

    try {
        testImap.getACL();
    } catch (final MessagingException e) {
        throw new MockTestException(e);
    }

}
 
Example 27
Source Project: streams   Source File: GMailMessageActivitySerializer.java    License: Apache License 2.0 5 votes vote down vote up
public GMailMessageActivitySerializer(GMailProvider provider) {

    this.provider = provider;

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, Boolean.FALSE);

    mapper.addMixInAnnotations(IMAPSSLStore.class, MessageMixIn.class);
    mapper.addMixInAnnotations(IMAPFolder.class, MessageMixIn.class);
    mapper.addMixInAnnotations(IMAPMessage.class, MessageMixIn.class);
    mapper.addMixInAnnotations(MimeMultipart.class, MessageMixIn.class);
    mapper.addMixInAnnotations(JavaMailGmailMessage.class, MessageMixIn.class);

  }
 
Example 28
Source Project: greenmail   Source File: ImapProtocolTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchUidsAndSize() throws MessagingException {
    store.connect("[email protected]", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("UID FETCH 1:* RFC822.SIZE", null);
            }
        });

        FetchResponse fetchResponse = (FetchResponse) ret[0];
        assertFalse(fetchResponse.isBAD());
        assertEquals(2, fetchResponse.getItemCount()); // UID and SIZE

        RFC822SIZE size = fetchResponse.getItem(RFC822SIZE.class);
        assertNotNull(size);
        assertTrue(size.size > 0);

        UID uid = fetchResponse.getItem(UID.class);
        assertEquals(folder.getUID(folder.getMessage(1)), uid.uid);
    } finally {
        store.close();
    }
}
 
Example 29
Source Project: greenmail   Source File: ImapProtocolTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRenameFolder() throws MessagingException {
    store.connect("[email protected]", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);
        Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("CREATE foo", null);
            }
        });

        IMAPResponse response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());

        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("RENAME foo bar", null);
            }
        });

        Response response2 = ret[0];
        assertTrue(response2.isOK());

        final Folder bar = store.getFolder("bar");
        bar.open(Folder.READ_ONLY);
        assertTrue(bar.exists());
    } finally {
        store.close();
    }
}
 
Example 30
Source Project: greenmail   Source File: ImapProtocolTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUidSearchTextWithCharset() throws MessagingException, IOException {
    greenMail.setUser("[email protected]", "pwd");
    store.connect("[email protected]", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);

        final MimeMessage email = GreenMailUtil.createTextEmail("[email protected]", "[email protected]",
                "some subject", "some content",
                greenMail.getSmtp().getServerSetup());

        String[][] s = {
                {"US-ASCII", "ABC", "1"},
                {"ISO-8859-15", "\u00c4\u00e4\u20AC", "2"},
                {"UTF-8", "\u00c4\u00e4\u03A0", "3"}
        };

        for (String[] charsetAndQuery : s) {
            final String charset = charsetAndQuery[0];
            final String search = charsetAndQuery[1];

            email.setSubject("subject " + search, charset);
            GreenMailUtil.sendMimeMessage(email);

            // messages[2] contains content with search text, match must be case insensitive
            final byte[] searchBytes = search.getBytes(charset);
            final Argument arg = new Argument();
            arg.writeBytes(searchBytes);
            // Try with and without quotes
            searchAndValidateWithCharset(folder, charsetAndQuery[2], charset, arg);
            searchAndValidateWithCharset(folder, charsetAndQuery[2], '"' + charset + '"', arg);
        }
    } finally {
        store.close();
    }
}