Java Code Examples for javax.mail.Flags

The following are top voted examples for showing how to use javax.mail.Flags. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: oscm   File: MailReader.java   Source Code and License 11 votes vote down vote up
/**
 * Connect to the mail server and delete all mails.
 */
public void deleteMails() throws MessagingException {
    Folder folder = getStore().getFolder(MAIL_INBOX);
    folder.open(Folder.READ_WRITE);

    // Get folder's list of messages.
    Message[] messages = folder.getMessages();

    // Retrieve message headers for each message in folder.
    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.ENVELOPE);
    folder.fetch(messages, profile);

    for (Message message : messages) {
        message.setFlag(Flags.Flag.DELETED, true);
    }
    folder.close(true);

}
 
Example 2
Project: openbd-core   File: cfImapConnection.java   Source Code and License 9 votes vote down vote up
public void changeStatus( String folderName, long mailIDs[], Flags.Flag newFlag, boolean value ){
  try{
  
    Folder folderToUse = mailStore.getFolder(folderName);
    folderToUse.open( Folder.READ_WRITE );
    
    Flags f = new Flags();
    f.add( newFlag );
	
	Message mlist[];
	if ( folderToUse instanceof UIDFolder )
		mlist = ((UIDFolder)folderToUse).getMessagesByUID( mailIDs );
	else
		mlist = folderToUse.getMessages( returnToInts(mailIDs) );
	
	for ( int x=0; x < mlist.length; x++ )
		mlist[x].setFlags( f, value );
    
    folderToUse.close( true );
	setData( "succeeded", 	cfBooleanData.TRUE );
  
  } catch (Exception E ){
	setData( "errortext", 	new cfStringData( E.getMessage() ) );
	setData( "succeeded", 	cfBooleanData.FALSE );
  }
}
 
Example 3
Project: alfresco-repository   File: AlfrescoImapFolder.java   Source Code and License 8 votes vote down vote up
/**
 *  Creates the EML message in the specified folder.
 *  
 *  @param folderFileInfo The folder to create message in.
 *  @param message The original MimeMessage.
 *  @return ID of the new message created 
 * @throws FileNotFoundException 
 * @throws FileExistsException 
 * @throws MessagingException 
 * @throws IOException 
 */
private long createMimeMessageInFolder(
        FileInfo folderFileInfo,
        MimeMessage message,
        Flags flags)
        throws FileExistsException, FileNotFoundException, IOException, MessagingException 
{
    String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate();
    FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
    FileInfo messageFile = fileFolderService.create(folderFileInfo.getNodeRef(), name, ContentModel.TYPE_CONTENT);
    final long newMessageUid = (Long) messageFile.getProperties().get(ContentModel.PROP_NODE_DBID);
    name = AlfrescoImapConst.MESSAGE_PREFIX  + newMessageUid + AlfrescoImapConst.EML_EXTENSION;
    fileFolderService.rename(messageFile.getNodeRef(), name);
    Flags newFlags = new Flags(flags);
    newFlags.add(Flag.RECENT);
    imapService.setFlags(messageFile, newFlags, true);
    
    if (extractAttachmentsEnabled)
    {
        imapService.extractAttachments(messageFile.getNodeRef(), message);
    }
    // Force persistence of the message to the repository
    new IncomingImapMessage(messageFile, serviceRegistry, message);
    return newMessageUid;        
}
 
Example 4
Project: omr   File: MailClient.java   Source Code and License 8 votes vote down vote up
public void checkInbox(int mode) throws MessagingException, IOException {
	if (mode == 0) {
		return;
	}
	boolean show = (mode & MailClient.SHOW_MESSAGES) > 0;
	boolean clear = (mode & MailClient.CLEAR_MESSAGES) > 0;
	String action = (show ? "Show" : "") + (show && clear ? " and " : "") + (clear ? "Clear" : "");
	System.out.println(action + " INBOX for " + from);
	Store store = session.getStore();
	store.connect();
	Folder root = store.getDefaultFolder();
	Folder inbox = root.getFolder("inbox");
	inbox.open(Folder.READ_WRITE);
	Message[] msgs = inbox.getMessages();
	if (msgs.length == 0 && show) {
		System.out.println("No messages in inbox");
	}
	for (Message msg2 : msgs) {
		MimeMessage msg = (MimeMessage) msg2;
		if (show) {
			System.out.println("    From: " + msg.getFrom()[0]);
			System.out.println(" Subject: " + msg.getSubject());
			System.out.println(" Content: " + msg.getContent());
		}
		if (clear) {
			msg.setFlag(Flags.Flag.DELETED, true);
		}
	}
	inbox.close(true);
	store.close();
	System.out.println();
}
 
Example 5
Project: alfresco-repository   File: ImapServiceImpl.java   Source Code and License 7 votes vote down vote up
/**
 * Return flags that belong to the specified imap folder.
 * 
 * @param messageInfo imap folder info.
 * @return flags.
 */
public Flags getFlags(FileInfo messageInfo)
{
    Flags flags = new Flags();
    Map<QName, Serializable> props = nodeService.getProperties(messageInfo.getNodeRef());

    for (QName key : qNameToFlag.keySet())
    {
        Boolean value = (Boolean) props.get(key);
        if (value != null && value)
        {
            flags.add(qNameToFlag.get(key));
        }
    }
    
    return flags;
}
 
Example 6
Project: alfresco-repository   File: AlfrescoImapFolder.java   Source Code and License 7 votes vote down vote up
/**
 * Replaces flags for the message with the given UID. If {@code addUid} is set to {@code true}
 * {@link FolderListener} objects defined for this folder will be notified.
 * {@code silentListener} can be provided - this listener wouldn't be notified.
 * 
 * @param flags - new flags.
 * @param uid - message UID.
 * @param silentListener - listener that shouldn't be notified.
 * @param addUid - defines whether or not listeners be notified.
 * @throws FolderException 
 * @throws MessagingException 
 */
@Override
protected void replaceFlagsInternal(
        Flags flags,
        long uid,
        FolderListener silentListener,
        boolean addUid)
        throws FolderException, MessagingException 
{
    int msn = getMsn(uid);
    FileInfo fileInfo = searchMails().get(uid);
    imapService.setFlags(fileInfo, MessageFlags.ALL_FLAGS, false);
    imapService.setFlags(fileInfo, flags, true);
    
    Long uidNotification = addUid ? uid : null;
    notifyFlagUpdate(msn, flags, uidNotification, silentListener);
}
 
Example 7
Project: alfresco-greenmail   File: RsetCommand.java   Source Code and License 7 votes vote down vote up
public void execute(Pop3Connection conn, Pop3State state, String cmd) {
    conn.println("+OK");
    try {
        MailFolder inbox = state.getFolder();
        List msgList = inbox.getMessages();
        int count = 0;
        for(int i=0;i<msgList.size();i++) {
            SimpleStoredMessage msg = (SimpleStoredMessage) msgList.get(i);
            Flags flags = msg.getFlags();
            if (flags.contains(Flags.Flag.DELETED)) {
                count++;
                flags.remove(Flags.Flag.DELETED);
            }
        }

        conn.println("+OK maildrop has "+count+" messages undeleted.");
    } catch (Exception e) {
        conn.println("-ERR " + e);
    }
}
 
Example 8
Project: alfresco-greenmail   File: InMemoryStore.java   Source Code and License 7 votes vote down vote up
public long appendMessage(MimeMessage message,
                                  Flags flags,
                                  Date internalDate) {
            long uid = nextUid;
            nextUid++;

//            flags.setRecent(true);
            SimpleStoredMessage storedMessage = new SimpleStoredMessage(message, flags,
                    internalDate, uid);
            storedMessage.getFlags().add(Flags.Flag.RECENT);

            mailMessages.add(storedMessage);
            int newMsn = mailMessages.size();

            // Notify all the listeners of the new message
            synchronized (_mailboxListeners) {
                for (int j = 0; j < _mailboxListeners.size(); j++) {
                    FolderListener listener = (FolderListener) _mailboxListeners.get(j);
                    listener.added(newMsn);
                }
            }

            return uid;
        }
 
Example 9
Project: product-ei   File: GreenMailServer.java   Source Code and License 7 votes vote down vote up
/**
 * Delete all emails in the inbox.
 *
 * @param protocol protocol used to connect to the server
 * @throws MessagingException if we're unable to connect to the store
 */
public static void deleteAllEmails(String protocol, GreenMailUser user) throws MessagingException {
    Folder inbox = null;
    Store store = getConnection(user, protocol);
    try {
        inbox = store.getFolder(EMAIL_INBOX);
        inbox.open(Folder.READ_WRITE);
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            message.setFlag(Flags.Flag.DELETED, true);
            log.info("Deleted email Subject : " + message.getSubject());
        }
    } finally {
        if (inbox != null) {
            inbox.close(true);
        }
        if (store != null) {
            store.close();
        }
    }
}
 
Example 10
Project: Unicorn   File: EmailUtilTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testSendingAndReceiving() throws MessagingException {
	Session session = EmailUtils.getGMailSession(EmailUtils.user, EmailUtils.pass);
	String key = (new Long(System.currentTimeMillis())).toString();
	EmailUtils.postMail(session, EmailUtils.user, "test" + key, "testmsg" + key);
	Folder inbox = EmailUtils.openPop3InboxReadWrite(session);
	Folder trash = EmailUtils.openPop3TrashReadWrite(session);
	boolean emailReceived = false;
	for (Message m : inbox.getMessages()) {
		if (m.getSubject().startsWith("test" + key)) {
			emailReceived = true;
			Message[] m_array = inbox.getMessages(m.getMessageNumber(), m.getMessageNumber());
			// delete test mail
			inbox.copyMessages(m_array, trash);
			m.setFlag(Flags.Flag.DELETED, true);
		}
	}
	EmailUtils.closeFolder(inbox);
	EmailUtils.closeFolder(trash);
	assertTrue(emailReceived);
}
 
Example 11
Project: Camel   File: MailDoNotDeleteIfProcessFailsTest.java   Source Code and License 7 votes vote down vote up
private void prepareMailbox() throws Exception {
    // connect to mailbox
    Mailbox.clearAll();

    JavaMailSender sender = new DefaultJavaMailSender();
    Store store = sender.getSession().getStore("imap");
    store.connect("localhost", 25, "claus", "secret");
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    folder.expunge();

    // inserts two new messages
    Message[] msg = new Message[2];
    msg[0] = new MimeMessage(sender.getSession());
    msg[0].setText("Message 1");
    msg[0].setHeader("Message-ID", "0");
    msg[0].setFlag(Flags.Flag.SEEN, false);
    msg[1] = new MimeMessage(sender.getSession());
    msg[1].setText("Message 2");
    msg[0].setHeader("Message-ID", "1");
    msg[1].setFlag(Flags.Flag.SEEN, true);
    folder.appendMessages(msg);
    folder.close(true);
}
 
Example 12
Project: Camel   File: MailProcessOnlyUnseenMessagesTest.java   Source Code and License 7 votes vote down vote up
private void prepareMailbox() throws Exception {
    // connect to mailbox
    Mailbox.clearAll();
    JavaMailSender sender = new DefaultJavaMailSender();
    Store store = sender.getSession().getStore("imap");
    store.connect("localhost", 25, "claus", "secret");
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    folder.expunge();

    // inserts two messages with the SEEN flag
    Message[] msg = new Message[2];
    msg[0] = new MimeMessage(sender.getSession());
    msg[0].setText("Message 1");
    msg[0].setHeader("Message-ID", "0");
    msg[0].setFlag(Flags.Flag.SEEN, true);
    msg[1] = new MimeMessage(sender.getSession());
    msg[1].setText("Message 2");
    msg[0].setHeader("Message-ID", "1");
    msg[1].setFlag(Flags.Flag.SEEN, true);
    folder.appendMessages(msg);
    folder.close(true);
}
 
Example 13
Project: development   File: MailReader.java   Source Code and License 7 votes vote down vote up
/**
 * Connect to the mail server and delete all mails.
 */
public void deleteMails() throws MessagingException {
    Folder folder = getStore().getFolder(MAIL_INBOX);
    folder.open(Folder.READ_WRITE);

    // Get folder's list of messages.
    Message[] messages = folder.getMessages();

    // Retrieve message headers for each message in folder.
    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.ENVELOPE);
    folder.fetch(messages, profile);

    for (Message message : messages) {
        message.setFlag(Flags.Flag.DELETED, true);
    }
    folder.close(true);

}
 
Example 14
Project: Ardulink-1   File: MailListener.java   Source Code and License 7 votes vote down vote up
private static void clear(Folder folder) throws MessagingException {
	if(folder.exists() && (folder.getType() & Folder.HOLDS_MESSAGES) == Folder.HOLDS_MESSAGES) {
		int totMessages = folder.getMessageCount();
		System.out.println(totMessages + " messages from folder: " + folder.getFullName());
		folder.open(Folder.READ_WRITE);
		Message[] messages = folder.getMessages();
		for (int i = 0; i < messages.length; i++) {
			System.out.println("Deleting message: " + (i+1) + " of " + totMessages);
			messages[i].setFlag(Flags.Flag.DELETED, true);
		}
		folder.close(true);
	}
	Folder[] childs = folder.list();
	for (int i = 0; i < childs.length; i++) {
		clear(childs[i]);
	}
}
 
Example 15
Project: omr   File: MailClient.java   Source Code and License 7 votes vote down vote up
public void checkInbox(int mode) throws MessagingException, IOException {
	if (mode == 0) {
		return;
	}
	boolean show = (mode & MailClient.SHOW_MESSAGES) > 0;
	boolean clear = (mode & MailClient.CLEAR_MESSAGES) > 0;
	String action = (show ? "Show" : "") + (show && clear ? " and " : "") + (clear ? "Clear" : "");
	System.out.println(action + " INBOX for " + from);
	Store store = session.getStore();
	store.connect();
	Folder root = store.getDefaultFolder();
	Folder inbox = root.getFolder("inbox");
	inbox.open(Folder.READ_WRITE);
	Message[] msgs = inbox.getMessages();
	if (msgs.length == 0 && show) {
		System.out.println("No messages in inbox");
	}
	for (Message msg2 : msgs) {
		MimeMessage msg = (MimeMessage) msg2;
		if (show) {
			System.out.println("    From: " + msg.getFrom()[0]);
			System.out.println(" Subject: " + msg.getSubject());
			System.out.println(" Content: " + msg.getContent());
		}
		if (clear) {
			msg.setFlag(Flags.Flag.DELETED, true);
		}
	}
	inbox.close(true);
	store.close();
	System.out.println();
}
 
Example 16
Project: omr   File: MailClient.java   Source Code and License 7 votes vote down vote up
public void checkInbox(int mode) throws MessagingException, IOException {
	if (mode == 0) {
		return;
	}
	boolean show = (mode & MailClient.SHOW_MESSAGES) > 0;
	boolean clear = (mode & MailClient.CLEAR_MESSAGES) > 0;
	String action = (show ? "Show" : "") + (show && clear ? " and " : "") + (clear ? "Clear" : "");
	System.out.println(action + " INBOX for " + from);
	Store store = session.getStore();
	store.connect();
	Folder root = store.getDefaultFolder();
	Folder inbox = root.getFolder("inbox");
	inbox.open(Folder.READ_WRITE);
	Message[] msgs = inbox.getMessages();
	if (msgs.length == 0 && show) {
		System.out.println("No messages in inbox");
	}
	for (Message msg2 : msgs) {
		MimeMessage msg = (MimeMessage) msg2;
		if (show) {
			System.out.println("    From: " + msg.getFrom()[0]);
			System.out.println(" Subject: " + msg.getSubject());
			System.out.println(" Content: " + msg.getContent());
		}
		if (clear) {
			msg.setFlag(Flags.Flag.DELETED, true);
		}
	}
	inbox.close(true);
	store.close();
	System.out.println();
}
 
Example 17
Project: omr   File: MailClient.java   Source Code and License 7 votes vote down vote up
public void checkInbox(int mode) throws MessagingException, IOException {
	if (mode == 0) {
		return;
	}
	boolean show = (mode & MailClient.SHOW_MESSAGES) > 0;
	boolean clear = (mode & MailClient.CLEAR_MESSAGES) > 0;
	String action = (show ? "Show" : "") + (show && clear ? " and " : "") + (clear ? "Clear" : "");
	System.out.println(action + " INBOX for " + from);
	Store store = session.getStore();
	store.connect();
	Folder root = store.getDefaultFolder();
	Folder inbox = root.getFolder("inbox");
	inbox.open(Folder.READ_WRITE);
	Message[] msgs = inbox.getMessages();
	if (msgs.length == 0 && show) {
		System.out.println("No messages in inbox");
	}
	for (Message msg2 : msgs) {
		MimeMessage msg = (MimeMessage) msg2;
		if (show) {
			System.out.println("    From: " + msg.getFrom()[0]);
			System.out.println(" Subject: " + msg.getSubject());
			System.out.println(" Content: " + msg.getContent());
		}
		if (clear) {
			msg.setFlag(Flags.Flag.DELETED, true);
		}
	}
	inbox.close(true);
	store.close();
	System.out.println();
}
 
Example 18
Project: omr   File: MailClient.java   Source Code and License 7 votes vote down vote up
public void checkInbox(int mode) throws MessagingException, IOException {
	if (mode == 0) {
		return;
	}
	boolean show = (mode & MailClient.SHOW_MESSAGES) > 0;
	boolean clear = (mode & MailClient.CLEAR_MESSAGES) > 0;
	String action = (show ? "Show" : "") + (show && clear ? " and " : "") + (clear ? "Clear" : "");
	System.out.println(action + " INBOX for " + from);
	Store store = session.getStore();
	store.connect();
	Folder root = store.getDefaultFolder();
	Folder inbox = root.getFolder("inbox");
	inbox.open(Folder.READ_WRITE);
	Message[] msgs = inbox.getMessages();
	if (msgs.length == 0 && show) {
		System.out.println("No messages in inbox");
	}
	for (Message msg2 : msgs) {
		MimeMessage msg = (MimeMessage) msg2;
		if (show) {
			System.out.println("    From: " + msg.getFrom()[0]);
			System.out.println(" Subject: " + msg.getSubject());
			System.out.println(" Content: " + msg.getContent());
		}
		if (clear) {
			msg.setFlag(Flags.Flag.DELETED, true);
		}
	}
	inbox.close(true);
	store.close();
	System.out.println();
}
 
Example 19
Project: Lucee   File: MailClient.java   Source Code and License 7 votes vote down vote up
/**
    * delete all message in ibox that match given criteria
    * @param messageNumbers
    * @param uIds
    * @throws MessagingException
 * @throws IOException 
    */
   public void deleteMails(String as[], String as1[]) throws MessagingException, IOException {
	Folder folder;
	Message amessage[];
	folder = _fldelse.getFolder("INBOX");
	folder.open(2);
	Map<String, Message> map = getMessages(null,folder, as1, as, startrow, maxrows,false);
	Iterator<String> iterator = map.keySet().iterator();
	amessage = new Message[map.size()];
	int i = 0;
	while(iterator.hasNext()) {
		amessage[i++] =  map.get(iterator.next());
	}
	try {
		folder.setFlags(amessage, new Flags(javax.mail.Flags.Flag.DELETED), true);
	}
	finally {
		folder.close(true);
	}
}
 
Example 20
Project: community-edition-old   File: ImapServiceImpl.java   Source Code and License 7 votes vote down vote up
@Override
public void onRestoreNode(final ChildAssociationRef childAssocRef)
{
    doAsSystem(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            NodeRef childNodeRef = childAssocRef.getChildRef();
            if (serviceRegistry.getDictionaryService().isSubClass(nodeService.getType(childNodeRef), ContentModel.TYPE_CONTENT))
            {
                setFlag(childNodeRef, Flags.Flag.DELETED, false);
                setFlag(childNodeRef, Flags.Flag.SEEN, false);
            }

            NodeRef folderRef = childAssocRef.getParentRef();
            long newId = (Long) nodeService.getProperty(childNodeRef, ContentModel.PROP_NODE_DBID);
            if (nodeService.hasAspect(folderRef, ImapModel.ASPECT_IMAP_FOLDER))
            {
                // Force generation of a new change token and updating the UIDVALIDITY 
                getUidValidityTransactionListener(folderRef).recordNewUid(newId);
            }
            return null;
        }
    });
}
 
Example 21
Project: community-edition-old   File: InMemoryStore.java   Source Code and License 7 votes vote down vote up
public long copyMessage(long uid, MailFolder toFolder)
        throws FolderException {
    SimpleStoredMessage originalMessage = getMessage(uid);
    MimeMessage newMime = null;
    try {
        newMime = new MimeMessage(originalMessage.getMimeMessage());
    } catch (MessagingException e) {
        // TODO chain.
        throw new FolderException("Messaging exception: " + e.getMessage());
    }
    Flags newFlags = new Flags();
    newFlags.add(originalMessage.getFlags());
    Date newDate = originalMessage.getInternalDate();

    return toFolder.appendMessage(newMime, newFlags, newDate);
}
 
Example 22
Project: javamaildir   File: MaildirMessage.java   Source Code and License 7 votes vote down vote up
public void setFlags(Flags f, boolean set)
            throws MessagingException {
        final Flags.Flag[] flags = f.getSystemFlags();
        boolean changed = false;

        for (int i = 0; i < flags.length; i++)
            changed = changed | (_setFlag(flags[i], set));

        log.debug("setFlags() changed: " + changed);

        if (!changed)
            return;

//        try {
//            updateFilename();
//        } catch (MessagingException mex) {
//            log.error(mex.toString());
//        }

        ((MaildirFolder) getFolder()).localNotifyMessageChangedListeners(MessageChangedEvent.FLAGS_CHANGED, FlagChangedEvent.getEventType(f, set), this);
    }
 
Example 23
Project: alfresco-repository   File: AbstractImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Appends message to the folder.
 * 
 * @param message - message.
 * @param flags - message flags.
 * @param internalDate - not used. Current date used instead.
 * @return long
 */
public long appendMessage(final MimeMessage message, final Flags flags, final Date internalDate) throws FolderException
{
    if (isReadOnly())
    {
        throw new FolderException("Can't append message - Permission denied");
    }

    CommandCallback<Long> command = new CommandCallback<Long>()
    {
        public Long command() throws Throwable
        {
            return appendMessageInternal(message, flags, internalDate);
        }
    };
    return command.runFeedback();
 }
 
Example 24
Project: alfresco-repository   File: AbstractImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Sets flags for the message with the given UID. If {@code addUid} is set to {@code true}
 * {@link FolderListener} objects defined for this folder will be notified.
 * {@code silentListener} can be provided - this listener wouldn't be notified.
 * 
 * @param flags - new flags.
 * @param value - flags value.
 * @param uid - message UID.
 * @param silentListener - listener that shouldn't be notified.
 * @param addUid - defines whether or not listeners be notified.
 */
public void setFlags(
        final Flags flags,
        final boolean value,
        final long uid,
        final FolderListener silentListener,
        final boolean addUid)
        throws FolderException
{
    CommandCallback<Object> command = new CommandCallback<Object>()
    {
        public Object command() throws Throwable
        {
            setFlagsInternal(flags, value, uid, silentListener, addUid);
            return null;
        }
    };
    command.runFeedback();
}
 
Example 25
Project: alfresco-repository   File: ImapServiceImpl.java   Source Code and License 6 votes vote down vote up
public void expungeMessage(FileInfo fileInfo)
{
    Flags flags = getFlags(fileInfo);
    if (flags.contains(Flags.Flag.DELETED))
    {
        // See MNT-12259
        //fileFolderService.delete(fileInfo.getNodeRef());
        hideAndDelete(fileInfo.getNodeRef());
        messageCache.remove(fileInfo.getNodeRef());
    }
}
 
Example 26
Project: alfresco-repository   File: ImapServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Set flags to the specified imapFolder.
 * 
 * @param messageInfo FileInfo of imap Folder.
 * @param flags flags to set.
 * @param value value to set.
 */
public void setFlags(FileInfo messageInfo, Flags flags, boolean value)
{
    checkForFlaggableAspect(messageInfo.getNodeRef());
    

    for (Flags.Flag flag : flags.getSystemFlags())
    {
        setFlag(messageInfo, flag, value);
    }
}
 
Example 27
Project: alfresco-repository   File: ImapServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void onRestoreNode(final ChildAssociationRef childAssocRef)
{
    doAsSystem(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            NodeRef childNodeRef = childAssocRef.getChildRef();
            if (serviceRegistry.getDictionaryService().isSubClass(nodeService.getType(childNodeRef), ContentModel.TYPE_CONTENT))
            {
                setFlag(childNodeRef, Flags.Flag.DELETED, false);
                setFlag(childNodeRef, Flags.Flag.SEEN, false);
            }

            NodeRef folderRef = childAssocRef.getParentRef();
            long newId = (Long) nodeService.getProperty(childNodeRef, ContentModel.PROP_NODE_DBID);
            if (nodeService.hasAspect(folderRef, ImapModel.ASPECT_IMAP_FOLDER))
            {
                // Force generation of a new change token and updating the UIDVALIDITY 
                getUidValidityTransactionListener(folderRef).recordNewUid(newId);
            }
            return null;
        }
    });
}
 
Example 28
Project: alfresco-repository   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Appends message to the folder.
 * 
 * @param message - message.
 * @param flags - message flags.
 * @param internalDate - not used. Current date used instead.
 */
@Override
protected long appendMessageInternal(
        MimeMessage message,
        Flags flags,
        Date internalDate)
        throws FileExistsException, FileNotFoundException, IOException, MessagingException 
{
    long uid;
    NodeRef sourceNodeRef = extractNodeRef(message);
    if (sourceNodeRef != null)
    {
        uid = copyOrMoveNode(this.folderInfo, message, flags, sourceNodeRef, false);
    }
    else
    {
        uid = createMimeMessageInFolder(this.folderInfo, message, flags);
    }
    // Invalidate current folder status
    this.folderStatus = null;
    return uid;
}
 
Example 29
Project: alfresco-repository   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Moves the node <code>sourceNodeRef</code> extracted from the message id.
 * A part of a complex move operation.
 * 
 * @param folderInfo FileInfo
 * @param message MimeMessage
 * @param flags Flags
 * @param sourceNodeRef NodeRef
 * @return UUID of the moved node
 * @throws FileExistsException
 * @throws FileNotFoundException
 */
@SuppressWarnings("deprecation")
private long copyOrMoveNode(FileInfo folderInfo, MimeMessage message, Flags flags, NodeRef sourceNodeRef, boolean move)
        throws FileExistsException, FileNotFoundException
{
    FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
    FileFilterMode.setClient(FileFilterMode.Client.imap);
    FileInfo messageFile = null;
    if (move)
    {
        fileFolderService.setHidden(sourceNodeRef, false);
        messageFile = fileFolderService.move(sourceNodeRef, folderInfo.getNodeRef(), null);
    }
    else
    {
        NodeRef newNodeRef = serviceRegistry.getCopyService().copyAndRename(sourceNodeRef, folderInfo.getNodeRef(), ContentModel.ASSOC_CONTAINS, null, false);
        fileFolderService.setHidden(newNodeRef, false);
        messageFile = fileFolderService.getFileInfo(newNodeRef);
    }
    final long newMessageUid = (Long) messageFile.getProperties().get(ContentModel.PROP_NODE_DBID);
    
    imapService.persistMessageHeaders(messageFile.getNodeRef(), message);
    
    Flags newFlags = new Flags(flags);
    newFlags.add(Flag.RECENT);
    
    imapService.setFlags(messageFile, newFlags, true);
    imapService.setFlag(messageFile, Flag.DELETED, false);
    
    return newMessageUid;
}
 
Example 30
Project: alfresco-repository   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Marks all messages in the folder as deleted using {@link javax.mail.Flags.Flag#DELETED} flag.
 */
@Override
public void deleteAllMessagesInternal() throws FolderException
{
    if (isReadOnly())
    {
        throw new FolderException("Can't delete all - Permission denied");
    }
    
    for (Map.Entry<Long, FileInfo> entry : searchMails().entrySet())
    {
        imapService.setFlag(entry.getValue(), Flags.Flag.DELETED, true);
        // comment out to physically remove content.
        // fileFolderService.delete(fileInfo.getNodeRef());
    }
}
 
Example 31
Project: alfresco-repository   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the list of messages that have no {@link javax.mail.Flags.Flag#DELETED} flag set for current user.
 * 
 * @return the list of non-deleted messages.
 */
@Override
protected List<SimpleStoredMessage> getNonDeletedMessagesInternal()
{
    if (logger.isDebugEnabled())
    {
        logger.debug("[getNonDeletedMessagesInternal] " + this);
    }
    List<SimpleStoredMessage> result = new ArrayList<SimpleStoredMessage>();

    Collection<SimpleStoredMessage> values = getMessagesInternal();
    for (SimpleStoredMessage message : values)
    {
        if (!getFlags(message).contains(Flags.Flag.DELETED))
        {
            result.add(message);
        }

    }
    if (logger.isDebugEnabled() && folderInfo != null)
    {
        logger.debug(folderInfo.getName() + " - Non deleted messages count:" + result.size());
    }
    return result;
}
 
Example 32
Project: alfresco-repository   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Returns count of messages with {@link javax.mail.Flags.Flag#RECENT} flag.
 * If {@code reset} parameter is {@code true} - removes {@link javax.mail.Flags.Flag#RECENT} flag from
 * the message for current user.
 * 
 * @param reset - if true the {@link javax.mail.Flags.Flag#RECENT} will be deleted for current user if exists.
 * @return returns count of recent messages.
 */
@Override
public int getRecentCount(boolean reset)
{
    int recent = getFolderStatus().recentCount;
    if (reset && recent > 0)
    {
        CommandCallback<Void> command = new CommandCallback<Void>()
        {
            public Void command() throws Throwable
            {
                for (FileInfo fileInfo : folderStatus.search.values())
                {
                    Flags flags = imapService.getFlags(fileInfo);
                    if (flags.contains(Flags.Flag.RECENT))
                    {
                        imapService.setFlag(fileInfo, Flags.Flag.RECENT, false);
                    }
                }
                return null;
            }
        };
        try
        {
            command.run();
        }
        catch (AccessDeniedException ade)
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("Access denied to reset RECENT FLAG");
            }
        }
    }
    return recent;        
}
 
Example 33
Project: alfresco-repository   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Sets flags for the message with the given UID. If {@code addUid} is set to {@code true}
 * {@link FolderListener} objects defined for this folder will be notified.
 * {@code silentListener} can be provided - this listener wouldn't be notified.
 * 
 * @param flags - new flags.
 * @param value - flags value.
 * @param uid - message UID.
 * @param silentListener - listener that shouldn't be notified.
 * @param addUid - defines whether or not listeners be notified.
 * @throws MessagingException 
 * @throws FolderException 
 */
@Override
protected void setFlagsInternal(
        Flags flags,
        boolean value,
        long uid,
        FolderListener silentListener,
        boolean addUid)
        throws MessagingException, FolderException 
{
    int msn = getMsn(uid);
    FileInfo fileInfo = searchMails().get(uid);
    imapService.setFlags(fileInfo, flags, value);
    
    Long uidNotification = null;
    if (addUid)
    {
        uidNotification = new Long(uid);
    }
    notifyFlagUpdate(msn, flags, uidNotification, silentListener);

}
 
Example 34
Project: alfresco-repository   File: ImapServiceImplTest.java   Source Code and License 6 votes vote down vote up
public void testSetFlag() throws Exception
{
    NavigableMap<Long, FileInfo> fis = imapService.getFolderStatus(authenticationService.getCurrentUserName(), testImapFolderNodeRef, ImapViewMode.ARCHIVE).search;
    if (fis != null && fis.size() > 0)
    {
        FileInfo messageFileInfo = fis.firstEntry().getValue();
        
        reauthenticate(USER_NAME, USER_PASSWORD);
        
        permissionService.setPermission(testImapFolderNodeRef, anotherUserName, PermissionService.WRITE, true);
        
        reauthenticate(anotherUserName, anotherUserName);
        
        imapService.setFlag(messageFileInfo, Flags.Flag.RECENT, true);
        
        Serializable prop = nodeService.getProperty(messageFileInfo.getNodeRef(), ImapModel.PROP_FLAG_RECENT);
        assertNotNull("Can't set RECENT flag", prop);
    }
}
 
Example 35
Project: alfresco-repository   File: ImapServiceImplTest.java   Source Code and License 6 votes vote down vote up
public void testGetFlags() throws Exception
{
    NavigableMap<Long, FileInfo> fis = imapService.getFolderStatus(authenticationService.getCurrentUserName(), testImapFolderNodeRef, ImapViewMode.ARCHIVE).search;
    if (fis != null && fis.size() > 0)
    {
        FileInfo messageFileInfo = fis.firstEntry().getValue();
        
        reauthenticate(USER_NAME, USER_PASSWORD);
        
        permissionService.setPermission(testImapFolderNodeRef, anotherUserName, PermissionService.WRITE, true);
        
        imapService.setFlags(messageFileInfo, flags, true);
        
        reauthenticate(anotherUserName, anotherUserName);

        Flags fl = imapService.getFlags(messageFileInfo);
        assertTrue(fl.contains(flags));
    }
}
 
Example 36
Project: alfresco-greenmail   File: SearchTermBuilder.java   Source Code and License 6 votes vote down vote up
private static javax.mail.Flags.Flag toFlag(String pFlag) {
    if (pFlag == null || pFlag.trim().length() < 1) {
        throw new IllegalArgumentException("Can not convert empty string to mail flag");
    }
    pFlag = pFlag.trim().toUpperCase();
    if (pFlag.equals("ANSWERED")) {
        return javax.mail.Flags.Flag.ANSWERED;
    }
    if (pFlag.equals("DELETED")) {
        return javax.mail.Flags.Flag.DELETED;
    }
    if (pFlag.equals("DRAFT")) {
        return javax.mail.Flags.Flag.DRAFT;
    }
    if (pFlag.equals("FLAGGED")) {
        return javax.mail.Flags.Flag.FLAGGED;
    }
    if (pFlag.equals("RECENT")) {
        return javax.mail.Flags.Flag.RECENT;
    }
    if (pFlag.equals("SEEN")) {
        return javax.mail.Flags.Flag.SEEN;
    }
    return null;
}
 
Example 37
Project: alfresco-greenmail   File: RetrCommand.java   Source Code and License 6 votes vote down vote up
public void execute(Pop3Connection conn, Pop3State state,
                    String cmd) {
    try {
        MailFolder inbox = state.getFolder();
        String[] cmdLine = cmd.split(" ");

        String msgNumStr = cmdLine[1];
        List msgList = inbox.getMessages(new MsgRangeFilter(msgNumStr, false));
        if (msgList.size() != 1) {
            conn.println("-ERR no such message");

            return;
        }

        SimpleStoredMessage msg = (SimpleStoredMessage) msgList.get(0);
        String email = GreenMailUtil.getWholeMessage(msg.getMimeMessage());
        conn.println("+OK");
        conn.print(new StringReader(email));
        conn.println();
        conn.println(".");
        msg.getFlags().add(Flags.Flag.SEEN);
    } catch (Exception e) {
        conn.println("-ERR " + e);
    }
}
 
Example 38
Project: alfresco-greenmail   File: InMemoryStore.java   Source Code and License 6 votes vote down vote up
public void setFlags(Flags flags, boolean value, long uid, FolderListener silentListener, boolean addUid) throws FolderException {
    int msn = getMsn(uid);
    SimpleStoredMessage message = (SimpleStoredMessage) mailMessages.get(msn - 1);

    if (value) {
        message.getFlags().add(flags);
    } else {
        message.getFlags().remove(flags);
    }

    Long uidNotification = null;
    if (addUid) {
        uidNotification = new Long(uid);
    }
    notifyFlagUpdate(msn, message.getFlags(), uidNotification, silentListener);
}
 
Example 39
Project: alfresco-greenmail   File: MessageFlags.java   Source Code and License 6 votes vote down vote up
/**
 * Returns IMAP formatted String of MessageFlags for named user
 */
public static String format(Flags flags) {
    StringBuffer buf = new StringBuffer();
    buf.append("(");
    if (flags.contains(Flags.Flag.ANSWERED)) {
        buf.append("\\Answered ");
    }
    if (flags.contains(Flags.Flag.DELETED)) {
        buf.append("\\Deleted ");
    }
    if (flags.contains(Flags.Flag.DRAFT)) {
        buf.append("\\Draft ");
    }
    if (flags.contains(Flags.Flag.FLAGGED)) {
        buf.append("\\Flagged ");
    }
    if (flags.contains(Flags.Flag.RECENT)) {
        buf.append("\\Recent ");
    }
    if (flags.contains(Flags.Flag.SEEN)) {
        buf.append("\\Seen ");
    }
    // Remove the trailing space, if necessary.
    if (buf.length() > 1) {
        buf.setLength(buf.length() - 1);
    }
    buf.append(")");
    return buf.toString();
}
 
Example 40
Project: ats-framework   File: ImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Cleans up the associated IMAP folder
 * @throws RbvStorageException
 */
@PublicAtsApi
public void expunge() throws RbvStorageException {

    //first check if the folder is open
    if (!isOpen) {
        throw new MatchableNotOpenException(getDescription() + " is not open");
    }

    try {
        folder.setFlags(folder.getMessages(), new Flags(Flags.Flag.DELETED), true);
        folder.expunge();
    } catch (MessagingException me) {
        throw new RbvStorageException(me);
    }

    log.info("Expunged " + getDescription());
}
 
Example 41
Project: jsf-core   File: ReciveMail.java   Source Code and License 6 votes vote down vote up
/**  
 * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】  
 */  
public boolean isNew() throws MessagingException {   
    boolean isnew = false;   
    Flags flags = ((Message) mimeMessage).getFlags();   
    Flags.Flag[] flag = flags.getSystemFlags();   
    logger.info("flags's length: " + flag.length);   
    for (int i = 0; i < flag.length; i++) {   
        if (flag[i] == Flags.Flag.SEEN) {   
            isnew = true;   
            logger.info("seen Message.......");   
            break;   
        }   
    }   
    return isnew;   
}
 
Example 42
Project: mdw   File: MDWEmailListener.java   Source Code and License 6 votes vote down vote up
public void process(Message[] messages) throws ListenerException {
    try {
        for (Message message : messages){
            String emailXml = createEmailXml(message);
            if (! StringHelper.isEmpty(emailXml)) {
                ListenerHelper helper = new ListenerHelper();
                Map<String,String> metaInfo = new HashMap<String,String>();
                metaInfo.put(Listener.METAINFO_PROTOCOL, Listener.METAINFO_PROTOCOL_EMAIL);
                metaInfo.put(Listener.METAINFO_SERVICE_CLASS, this.getClass().getName());
                helper.processEvent(emailXml, metaInfo);
                // Set Delete flag as true sothat this email will be marked as read or deleted based on property values
                message.setFlag(Flags.Flag.DELETED,true);
            }
        }
    } catch (Exception ex) {
        logger.severeException("Exception in MDWEmailListener "+ex.getMessage(), ex);
        throw new ListenerException("Exception in MDWEmailListener " + ex.getMessage());
    }
}
 
Example 43
Project: codenvy   File: MailReceiverUtils.java   Source Code and License 6 votes vote down vote up
/**
 * delete all mails in the test mailbox, exceptions that may be produced during working with test
 * mailbox:
 *
 * @throws MessagingException
 */
public void cleanMailBox() throws MessagingException {
  Properties properties = System.getProperties(); // Get system properties
  Session session = Session.getDefaultInstance(properties); // Get the default Session object.
  Store store =
      session.getStore("imaps"); // Get a Store object that implements the specified protocol.
  store.connect(
      host, user,
      password); // Connect to the current host using the specified username and password.
  Folder folder =
      store.getFolder("inbox"); // Create a Folder object corresponding to the given name.
  folder.open(Folder.READ_WRITE); // Open the Folder.
  Message[] messages = folder.getMessages();
  for (int i = 0, n = messages.length; i < n; i++) {
    messages[i].setFlag(Flags.Flag.DELETED, true);
  }
  closeStoreAndFolder(folder, store);
}
 
Example 44
Project: rest   File: EmlMailboxUtilService.java   Source Code and License 6 votes vote down vote up
/**
 * 테스트 메일 입력
 * @param userId 생성자의 메일 주소 또는 이메일 아이디(EML_USER 테이블 PK)
 * @param folderFullName 원래 메일함 경로
 * @param eml 메일 MIME 내용
 * @param cnt 입력 횟수
 */
public void appendMessage(String userId, String folderFullName, String eml, int cnt) throws MailboxException {
	MailboxSession session = null;
	try {
		session = loginMailboxByUserId(userId);
		mailboxmanager.startProcessingRequest(session);
		String userKey = session.getUser().getUserName();
		MailboxPath mailboxPath = new MailboxPath(session.getPersonalSpace(), userKey, folderFullName);
		MessageManager messageManager = mailboxmanager.getMailbox(mailboxPath, session);
		for (int i = 0; i < cnt; i++) {
			messageManager.appendMessage(new ByteArrayInputStream(eml.getBytes()), new Date(), session, true,
					new Flags());
		}
       } finally {
		 if (session != null) {
			 mailboxmanager.endProcessingRequest(session);
             try {
            	 mailboxmanager.logout(session, true);
             } catch (MailboxException e) {
               	e.printStackTrace();
             }
         }
	}
}
 
Example 45
Project: rest   File: EmlMailboxUtilService.java   Source Code and License 6 votes vote down vote up
/**
 * 메일함에 Mime Message를 저장한다.
 * @param userId 생성자의 메일 주소 또는 이메일 아이디(EML_USER 테이블 PK)
 * @param folderFullName 원래 메일함 경로
 * @param eml 메일 MIME 내용
 * @throws javax.mail.MessagingException
 * @throws java.io.IOException
 * @throws org.apache.james.mailbox.exception.MailboxException
 */
public void appendMessage(String userId, String folderFullName, String eml)
		throws IOException, MessagingException, MailboxException {
	MailboxSession session = null;
	try {
		session = loginMailboxByUserId(userId);
		mailboxmanager.startProcessingRequest(session);
		String userKey = session.getUser().getUserName();
		MailboxPath mailboxPath = new MailboxPath(session.getPersonalSpace(), userKey, folderFullName);
		MessageManager messageManager = mailboxmanager.getMailbox(mailboxPath, session);
		messageManager.appendMessage(new ByteArrayInputStream(eml.getBytes()), new Date(), session, true,
				new Flags());
	} finally {
		 if (session != null) {
			 mailboxmanager.endProcessingRequest(session);
             try {
            	 mailboxmanager.logout(session, true);
             } catch (MailboxException e) {
               	e.printStackTrace();
             }
         }
	}
}
 
Example 46
Project: SmartTokens   File: MailBean.java   Source Code and License 6 votes vote down vote up
/**
 * For debugging
 */
public void displayMessages() {

	try {
		Folder inbox = store.getFolder("INBOX");
		inbox.open(Folder.READ_WRITE);

		int count = inbox.getMessageCount();
		Message[] messages = inbox.getMessages(1, count);
		for (Message message : messages) {
			if (!message.getFlags().contains(Flags.Flag.SEEN)) {
				Address[] fromAddresses = message.getFrom();
				System.out.println("...................");
				System.out.println("\t From: " + fromAddresses[0].toString());
				System.out.println("\t To: " + parseAddresses(message.getRecipients(RecipientType.TO)));
				System.out.println("\t CC: " + parseAddresses(message.getRecipients(RecipientType.CC)));
				System.out.println("\t Subject: " + message.getSubject());
				System.out.println("\t Sent Date:" + message.getSentDate().toString());
				try {
					System.out.println(message.getContent().toString());
				} catch (Exception ex) {
					System.out.println("Error reading content!!");
					ex.printStackTrace();
				}
			}
		}

		inbox.close(false);
		store.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 47
Project: mail-importer   File: JavaxMailMessage.java   Source Code and License 6 votes vote down vote up
@Override
public boolean isSet(Flags.Flag flag) throws RuntimeMessagingException {
  try {
    return delegate.isSet(flag);
  } catch (MessagingException e) {
    throw new RuntimeMessagingException(e);
  }
}
 
Example 48
Project: mail-importer   File: JavaxMailMessage.java   Source Code and License 6 votes vote down vote up
@Override
public void setFlag(Flags.Flag flag, boolean set)
    throws RuntimeMessagingException {
  try {
    delegate.setFlag(flag, set);
  } catch (MessagingException e) {
    throw new RuntimeMessagingException(e);
  }
}
 
Example 49
Project: BotLibre   File: Email.java   Source Code and License 6 votes vote down vote up
/**
 * Check the inbox for new messages, and process each message.
 */
public void checkEmail() {
	try {
		log("Checking email.", Level.INFO);
        Store store = connectStore();		
	    Folder inbox = store.getFolder("INBOX");
	    if (inbox == null) {
	      throw new BotException("Failed to check email, no INBOX.");
	    }
	    inbox.open(Folder.READ_WRITE);
           Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
           inbox.setFlags(messages, new Flags(Flags.Flag.SEEN), true);
	    //Message[] messages = inbox.getMessages();
	    if ((messages != null) && (messages.length > 0)) {
   			log("Processing emails", Level.INFO, messages.length);
			Network memory = getBot().memory().newMemory();
			Vertex sense = memory.createVertex(getPrimitive());
			Vertex vertex = sense.getRelationship(Primitive.LASTMESSAGE);
			long lastMessage = 0;
			if (vertex != null) {
				lastMessage = ((Number)vertex.getData()).longValue();
			}
			long maxMessage = 0;
			int count = 0;
			// Increase script timeout.
			Language language = getBot().mind().getThought(Language.class);
			int timeout = language.getMaxStateProcess();
			language.setMaxStateProcess(timeout * 2);
			try {
			    for (int index = 0; index < messages.length; index++) {
			    	if (index > (this.maxEmails * 2)) {
		    			log("Max old email limit reached", Level.WARNING, this.maxEmails * 2);
			    		break;
			    	}
			    	long recievedTime = 0;
			    	if (messages[index].getReceivedDate() == null) {
		    			log("Missing received date", Level.FINE, messages[index].getSubject());
			    		recievedTime = messages[index].getSentDate().getTime();
			    	} else {
			    		recievedTime = messages[index].getReceivedDate().getTime();
			    	}
			    	if ((System.currentTimeMillis() - recievedTime) > DAY) {
						log("Day old email", Level.INFO, messages[index].getSubject());
			    		continue;
			    	}
			    	if (recievedTime > lastMessage) {
			    		count++;
			    		if (count > this.maxEmails) {
			    			log("Max email limit reached", Level.WARNING, this.maxEmails);
			    			break;
			    		}
			    		input(messages[index]);
				    	Utils.sleep(100);
				    	if (recievedTime > maxMessage) {
				    		maxMessage = recievedTime;
				    	}
			    	}
			    }
			    if (maxMessage != 0) {
					sense.setRelationship(Primitive.LASTMESSAGE, memory.createVertex(maxMessage));
			    	memory.save();
			    }
			} finally {
				language.setMaxStateProcess(timeout);
			}
	    }
		log("Done checking email.", Level.INFO);
	    inbox.close(false);
	    store.close();
	} catch (MessagingException exception) {
		log(exception);
	}
}
 
Example 50
Project: BotLibre   File: Email.java   Source Code and License 6 votes vote down vote up
/**
 * Return a list in inbox message headers.
 */
public List<String> getInbox() {
	List<String> emails = new ArrayList<String>();
	Store store = null;
	Folder inbox = null;
	try {
		store = connectStore();		
	    inbox = store.getFolder("INBOX");
	    if (inbox == null) {
	      log(new BotException("Failed to access inbox, no INBOX."));
	    }
	    inbox.open(Folder.READ_ONLY);
	    
           Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
	    //Message[] messages = inbox.getMessages(1, Math.min(inbox.getMessageCount(), 50));
	    for (int index = 0; index < 10 && index < messages.length; index++) {
	      emails.add(0, messages[index].getReceivedDate() + " - " + String.valueOf(getFrom(messages[index])) + ": " + messages[index].getSubject());
	    }
	    inbox.close(false);
	    store.close();
	} catch (MessagingException exception) {
		log(new BotException("Failed to access email: " + exception.getMessage(), exception));
	} finally {
		try {
			if (inbox != null) {
				inbox.close(false);
			}
			if (store != null) {
				store.close();
			}
		} catch (Exception ignore) {}
	}
	return emails;
}
 
Example 51
Project: elpi   File: JavaMailContainer.java   Source Code and License 6 votes vote down vote up
protected void checkMessages(Store store, Session session) throws MessagingException {
    if (!store.isConnected()) {
        store.connect();
    }

    // open the default folder
    Folder folder = store.getDefaultFolder();
    if (!folder.exists()) {
        throw new MessagingException("No default (root) folder available");
    }

    // open the inbox
    folder = folder.getFolder(INBOX);
    if (!folder.exists()) {
        throw new MessagingException("No INBOX folder available");
    }

    // get the message count; stop if nothing to do
    folder.open(Folder.READ_WRITE);
    int totalMessages = folder.getMessageCount();
    if (totalMessages == 0) {
        folder.close(false);
        return;
    }

    // get all messages
    Message[] messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.ENVELOPE);
    profile.add(FetchProfile.Item.FLAGS);
    profile.add("X-Mailer");
    folder.fetch(messages, profile);

    // process each message
    for (Message message: messages) {
        // process each un-read message
        if (!message.isSet(Flags.Flag.SEEN)) {
            long messageSize = message.getSize();
            if (message instanceof MimeMessage && messageSize >= maxSize) {
                Debug.logWarning("Message from: " + message.getFrom()[0] + "not received, too big, size:" + messageSize + " cannot be more than " + maxSize + " bytes", module);

                // set the message as read so it doesn't continue to try to process; but don't delete it
                message.setFlag(Flags.Flag.SEEN, true);
            } else {
                this.processMessage(message, session);
                if (Debug.verboseOn()) Debug.logVerbose("Message from " + UtilMisc.toListArray(message.getFrom()) + " with subject [" + message.getSubject() + "]  has been processed." , module);
                message.setFlag(Flags.Flag.SEEN, true);
                if (Debug.verboseOn()) Debug.logVerbose("Message [" + message.getSubject() + "] is marked seen", module);

                // delete the message after processing
                if (deleteMail) {
                    if (Debug.verboseOn()) Debug.logVerbose("Message [" + message.getSubject() + "] is being deleted", module);
                    message.setFlag(Flags.Flag.DELETED, true);
                }
            }
        }
    }

    // expunge and close the folder
    folder.close(true);
}
 
Example 52
Project: Leboncoin   File: MailManager.java   Source Code and License 6 votes vote down vote up
public synchronized static boolean doActionGmail(MessageProcess f,
		int attempts) {
	try {
		Properties props = System.getProperties();
		props.setProperty("mail.smtp.host", "smtp.gmail.com");
		props.setProperty("mail.smtp.socketFactory.port", "465");
		props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.smtp.port", "465");
		
		Session session = Session.getDefaultInstance(props, null);
		Store store = session.getStore("imaps");
		store.connect("smtp.gmail.com", DefaultUserConf.EMAIL,
				DefaultUserConf.PASSWORD);

		Folder inbox = store.getFolder("Inbox");
		inbox.open(Folder.READ_WRITE);

		// Get directory
		Flags seen = new Flags(Flags.Flag.SEEN);
		FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
		Message messages[] = inbox.search(unseenFlagTerm);

		for (int i = 0; i < messages.length; i++) {
			f.treatMessage(messages[i]);
		}

		// Close connection
		inbox.close(true);
		store.close();

		return true;
	} catch (Exception e) {
		Logger.traceERROR(e);
		Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
		if (attempts > MAX_ATTEMPS) {
			return false;
		} else {
			doActionGmail(f, attempts++);
		}
	}
	return false;
}
 
Example 53
Project: Leboncoin   File: MailManager.java   Source Code and License 6 votes vote down vote up
public synchronized static boolean doActionAEI(MessageProcess f,
		int attempts) {
	try {
		Properties props = new Properties();
		props.put("mail.smtp.host", "ssl0.ovh.net");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");

		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(
								"philippe.remy%junior-aei.com", "phremy");
					}
				});

		Store store = session.getStore("imap");
		store.connect("ssl0.ovh.net", "philippe.remy%junior-aei.com",
				"phremy");

		// Get folder
		Folder inbox = store.getFolder("INBOX");
		inbox.open(Folder.READ_WRITE);

		// Get directory
		Flags seen = new Flags(Flags.Flag.SEEN);
		FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
		Message messages[] = inbox.search(unseenFlagTerm);

		for (int i = 0; i < messages.length; i++) {
			f.treatMessage(messages[i]);
		}

		// Close connection
		inbox.close(true);
		store.close();

		return true;
	} catch (Exception e) {
		Logger.traceERROR(e);
		Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
		if (attempts > MAX_ATTEMPS) {
			return false;
		} else {
			doActionAEI(f, attempts++);
		}
	}

	return false;
}
 
Example 54
Project: cs-actions   File: GetMailMessageTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test execute method with default values for trustAllRoots(true), enableSSL(false)
 * subjectOnly(false), deleteUponRetrieval(false).
 *
 * @throws Exception
 */
@Test
public void testExecuteWithGivenCharacterSet() throws Exception {
    doReturn(messageMock).when(getMailMessageSpy).getMessage();
    doNothing().when(messageMock).setFlag(Flags.Flag.DELETED, true);
    doReturn(folderMock).when(messageMock).getFolder();
    doReturn(new String[]{"1"}).when(messageMock).getHeader(anyString());
    doReturn(SUBJECT_TEST).when(getMailMessageSpy).changeHeaderCharset("1", CHARACTERSET);

    addRequiredInputs();
    inputs.setSubjectOnly(STR_TRUE);
    inputs.setDeleteUponRetrieval(STR_TRUE);
    inputs.setCharacterSet(CHARACTERSET);

    Map<String, String> result = getMailMessageSpy.execute(inputs);
    assertEquals(SUBJECT_TEST, result.get(RETURN_RESULT));
    assertEquals(SUBJECT_TEST, result.get(SUBJECT_RESULT));
    verify(getMailMessageSpy).getMessage();
    verify(messageMock).getHeader("Subject");
    verify(getMailMessageSpy).changeHeaderCharset(anyString(), anyString());
}
 
Example 55
Project: community-edition-old   File: ImapServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Set flags to the specified imapFolder.
 * 
 * @param messageInfo FileInfo of imap Folder.
 * @param flags flags to set.
 * @param value value to set.
 */
public void setFlags(FileInfo messageInfo, Flags flags, boolean value)
{
    checkForFlaggableAspect(messageInfo.getNodeRef());
    

    for (Flags.Flag flag : flags.getSystemFlags())
    {
        setFlag(messageInfo, flag, value);
    }
}
 
Example 56
Project: community-edition-old   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Appends message to the folder.
 * 
 * @param message - message.
 * @param flags - message flags.
 * @param internalDate - not used. Current date used instead.
 */
@Override
protected long appendMessageInternal(
        MimeMessage message,
        Flags flags,
        Date internalDate)
        throws FileExistsException, FileNotFoundException, IOException, MessagingException 
{
    long uid;
    NodeRef sourceNodeRef = extractNodeRef(message);
    if (sourceNodeRef != null)
    {
        uid = copyOrMoveNode(this.folderInfo, message, flags, sourceNodeRef, false);
    }
    else
    {
        uid = createMimeMessageInFolder(this.folderInfo, message, flags);
    }
    // Invalidate current folder status
    this.folderStatus = null;
    return uid;
}
 
Example 57
Project: community-edition-old   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Marks all messages in the folder as deleted using {@link javax.mail.Flags.Flag#DELETED} flag.
 */
@Override
public void deleteAllMessagesInternal() throws FolderException
{
    if (isReadOnly())
    {
        throw new FolderException("Can't delete all - Permission denied");
    }
    
    for (Map.Entry<Long, FileInfo> entry : searchMails().entrySet())
    {
        imapService.setFlag(entry.getValue(), Flags.Flag.DELETED, true);
        // comment out to physically remove content.
        // fileFolderService.delete(fileInfo.getNodeRef());
    }
}
 
Example 58
Project: community-edition-old   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the list of messages that have no {@link javax.mail.Flags.Flag#DELETED} flag set for current user.
 * 
 * @return the list of non-deleted messages.
 */
@Override
protected List<SimpleStoredMessage> getNonDeletedMessagesInternal()
{
    if (logger.isDebugEnabled())
    {
        logger.debug("[getNonDeletedMessagesInternal] " + this);
    }
    List<SimpleStoredMessage> result = new ArrayList<SimpleStoredMessage>();

    Collection<SimpleStoredMessage> values = getMessagesInternal();
    for (SimpleStoredMessage message : values)
    {
        if (!getFlags(message).contains(Flags.Flag.DELETED))
        {
            result.add(message);
        }

    }
    if (logger.isDebugEnabled() && folderInfo != null)
    {
        logger.debug(folderInfo.getName() + " - Non deleted messages count:" + result.size());
    }
    return result;
}
 
Example 59
Project: community-edition-old   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Returns count of messages with {@link javax.mail.Flags.Flag#RECENT} flag.
 * If {@code reset} parameter is {@code true} - removes {@link javax.mail.Flags.Flag#RECENT} flag from
 * the message for current user.
 * 
 * @param reset - if true the {@link javax.mail.Flags.Flag#RECENT} will be deleted for current user if exists.
 * @return returns count of recent messages.
 */
@Override
public int getRecentCount(boolean reset)
{
    int recent = getFolderStatus().recentCount;
    if (reset && recent > 0)
    {
        CommandCallback<Void> command = new CommandCallback<Void>()
        {
            public Void command() throws Throwable
            {
                for (FileInfo fileInfo : folderStatus.search.values())
                {
                    Flags flags = imapService.getFlags(fileInfo);
                    if (flags.contains(Flags.Flag.RECENT))
                    {
                        imapService.setFlag(fileInfo, Flags.Flag.RECENT, false);
                    }
                }
                return null;
            }
        };
        try
        {
            command.run();
        }
        catch (AccessDeniedException ade)
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("Access denied to reset RECENT FLAG");
            }
        }
    }
    return recent;        
}
 
Example 60
Project: community-edition-old   File: AlfrescoImapFolder.java   Source Code and License 6 votes vote down vote up
/**
 * Sets flags for the message with the given UID. If {@code addUid} is set to {@code true}
 * {@link FolderListener} objects defined for this folder will be notified.
 * {@code silentListener} can be provided - this listener wouldn't be notified.
 * 
 * @param flags - new flags.
 * @param value - flags value.
 * @param uid - message UID.
 * @param silentListener - listener that shouldn't be notified.
 * @param addUid - defines whether or not listeners be notified.
 * @throws MessagingException 
 * @throws FolderException 
 */
@Override
protected void setFlagsInternal(
        Flags flags,
        boolean value,
        long uid,
        FolderListener silentListener,
        boolean addUid)
        throws MessagingException, FolderException 
{
    int msn = getMsn(uid);
    FileInfo fileInfo = searchMails().get(uid);
    imapService.setFlags(fileInfo, flags, value);
    
    Long uidNotification = null;
    if (addUid)
    {
        uidNotification = new Long(uid);
    }
    notifyFlagUpdate(msn, flags, uidNotification, silentListener);

}