Java Code Examples for javax.mail.Message#setFlag()

The following examples show how to use javax.mail.Message#setFlag() . 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: GreenMailServer.java    From micro-integrator with Apache License 2.0 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 2
Source File: Email.java    From smslib-v3 with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<OutboundMessage> getMessagesToSend() throws Exception
{
	List<OutboundMessage> retValue = new ArrayList<OutboundMessage>();
	Store s = this.mailSession.getStore();
	s.connect();
	Folder inbox = s.getFolder(getProperty("mailbox_name", "INBOX"));
	inbox.open(Folder.READ_WRITE);
	for (Message m : inbox.getMessages())
	{
		OutboundMessage om = new OutboundMessage(m.getSubject(), m.getContent().toString());
		om.setFrom(m.getFrom().toString());
		om.setDate(m.getReceivedDate());
		retValue.add(om);
		// Delete message from inbox
		m.setFlag(Flags.Flag.DELETED, true);
	}
	inbox.close(true);
	s.close();
	return retValue;
}
 
Example 3
Source File: AbstractIMAPRiverUnitTest.java    From elasticsearch-imap with Apache License 2.0 6 votes vote down vote up
protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start, final int deleteCount,
        final String user, final String password) throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);
    f.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m = deleteCount == -1 ? f.getMessages() : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
        message.setFlag(Flag.DELETED, true);
        logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
        d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();

}
 
Example 4
Source File: MailReader.java    From development with Apache License 2.0 6 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 5
Source File: GreenMailServer.java    From product-ei with Apache License 2.0 6 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 6
Source File: Core.java    From FairEmail with 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 7
Source File: Core.java    From FairEmail with 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 8
Source File: Core.java    From FairEmail with 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 9
Source File: ImapFolder.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
public List<MetaData> getAllMetaData() throws RbvException {

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

        try {
            allMetaDataList.clear();
            newMetaDataList.clear();

            boolean hasNew = folder.hasNewMessages();
            log.debug("Has new messages in folder: " + hasNew);
            Message[] imapMessages = folder.getMessages();

            for (Message imapMessage : imapMessages) {

                ImapMetaData currentMeta = createImapMetaData((MimeMessage) imapMessage);
                if (currentMeta != null) {
                    if (!imapMessage.getFlags().contains(Flags.Flag.FLAGGED)) {
                        newMetaDataList.add(currentMeta);
                    }

                    imapMessage.setFlag(Flags.Flag.FLAGGED, true);

                    allMetaDataList.add(currentMeta);
                }
            }

            //this was the first pass
            isInitialPass = false;

            return allMetaDataList;

        } catch (MessagingException me) {
            throw new RbvStorageException("Could not get meta data from " + getDescription(), me);
        }
    }
 
Example 10
Source File: ImapFolder.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
public List<MetaData> getNewMetaData() throws RbvException {

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

        if (isInitialPass) {
            isInitialPass = false;
            return getAllMetaData();
        }

        try {
            newMetaDataList.clear();

            Message[] imapMessages = folder.getMessages();

            for (Message imapMessage : imapMessages) {
                if (!imapMessage.getFlags().contains(Flags.Flag.FLAGGED)) {
                    imapMessage.setFlag(Flags.Flag.FLAGGED, true);

                    ImapMetaData currentMeta = createImapMetaData((MimeMessage) imapMessage);
                    if (currentMeta != null) {
                        allMetaDataList.add(currentMeta);
                        newMetaDataList.add(currentMeta);
                    }
                }
            }
        } catch (MessagingException me) {
            throw new RbvStorageException("Could not get meta data from " + getDescription(), me);
        }

        return newMetaDataList;
    }
 
Example 11
Source File: EmailClient.java    From bobcat with Apache License 2.0 5 votes vote down vote up
/**
 * This method deletes mail
 *
 * @param message Mail reference
 */
private void removeEmail(Message message) {
  try {
    message.setFlag(Flags.Flag.DELETED, true);
  } catch (MessagingException e) {
    LOGGER.error("error when removing  emails from server", e);
  }
}
 
Example 12
Source File: MailReceiver.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 接收邮件.
 * @param expunge
 *            	邮件是否删除
 * @return List&lt;Message&gt;
 * 				收到的邮件集合
 * @throws MessagingException
 *             the messaging exception
 */
public List<Message> receive(boolean expunge) throws MessagingException {
	List<Message> result = new ArrayList<Message>();
	store = session.getStore();
	store.connect();
	Folder folder = store.getFolder("INBOX");
	folder.open(Folder.READ_WRITE);
	for (Message message : folder.getMessages()) {
		result.add(message);
		//设置邮件的 DELETED 标志
		message.setFlag(Flags.Flag.DELETED, expunge);
	}
	folderList.add(folder);
	return result;
}
 
Example 13
Source File: AbstractNotificationTaskITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static boolean pop3(final String sender, final String subject, final String mailAddress) throws Exception {
    boolean found = false;
    Store store = null;
    try {
        store = Session.getDefaultInstance(System.getProperties()).getStore("pop3");
        store.connect(POP3_HOST, POP3_PORT, mailAddress, mailAddress);

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

        Message[] messages = inbox.getMessages();
        for (Message message : messages) {
            if (sender.equals(message.getFrom()[0].toString()) && subject.equals(message.getSubject())) {
                found = true;
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }

        inbox.close(true);
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return found;
}
 
Example 14
Source File: MessageDeleter.java    From mnIMAPSync with Apache License 2.0 5 votes vote down vote up
public void run() {
    long deleted = 0L;
    long skipped = 0L;
    try {
        final Folder targetFolder = storeDeleter.getTargetStore().getFolder(targetFolderName);
        //Opens a new connection per Thread
        targetFolder.open(Folder.READ_WRITE);
        final Message[] targetMessages = targetFolder.getMessages(start, end);
        targetFolder.fetch(targetMessages, MessageId.addHeaders(new FetchProfile()));
        for (Message message : targetMessages) {
            try {
                final MessageId id = new MessageId(message);
                if (!sourceFolderMessages.contains(id)) {
                    message.setFlag(Flags.Flag.DELETED, true);
                    deleted++;
                } else {
                    skipped++;
                }
            } catch (MessageId.MessageIdException ex) {
                //Usually messages that ran into this exception are spammy, so we skip them.
                skipped++;
            }
        }
        //Close folder and expunge flagged messages
        //Expunge only if folder is read write
        if (targetFolder.getMode() == Folder.READ_ONLY) {
            targetFolder.close(false);
        } else {
            targetFolder.close(expunge);
        }
    } catch (MessagingException messagingException) {
        Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, messagingException);
    }
    storeDeleter.updatedMessagesDeletedCount(deleted);
    storeDeleter.updateMessagesSkippedCount(skipped);
}
 
Example 15
Source File: MailReceiver.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 接收邮件.
 * @param expunge
 *            	邮件是否删除
 * @return List&lt;Message&gt;
 * 				收到的邮件集合
 * @throws MessagingException
 *             the messaging exception
 */
public List<Message> receive(boolean expunge) throws MessagingException {
	List<Message> result = new ArrayList<Message>();
	store = session.getStore();
	store.connect();
	Folder folder = store.getFolder("INBOX");
	folder.open(Folder.READ_WRITE);
	for (Message message : folder.getMessages()) {
		result.add(message);
		//设置邮件的 DELETED 标志
		message.setFlag(Flags.Flag.DELETED, expunge);
	}
	folderList.add(folder);
	return result;
}
 
Example 16
Source File: Pop3Util.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
  * 标记为已读 
  * @param messages  messages
  */ 
 public static void seen(Message ...messages) {   
     for (int i = 0, count = messages.length; i < count; i++) {   
         Message message = messages[i]; 
         String subject; 
try { 
	subject = message.getSubject(); 
          message.setFlag(Flags.Flag.SEEN, true); 
          log.warn("[标记为已读][subject:{}]",subject);    
} catch (MessagingException e) { 
	e.printStackTrace(); 
}  
     } 
 }
 
Example 17
Source File: JavaMailContainer.java    From scipio-erp with Apache License 2.0 4 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 18
Source File: EmailUtil.java    From product-es with Apache License 2.0 4 votes vote down vote up
/**
 * This method read verification e-mail from Gmail inbox and returns the verification URL.
 *
 * @return  verification redirection URL.
 * @throws  Exception
 */
public static String readGmailInboxForVerification() throws Exception {
    boolean isEmailVerified = false;
    long waitTime = 10000;
    String pointBrowserURL = "";
    Properties props = new Properties();
    props.load(new FileInputStream(new File(
            TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
                    + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);
    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isEmailVerified) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());
                    if (message.getSubject().contains("EmailVerification")) {
                        pointBrowserURL = getBodyFromMessage(message);
                        isEmailVerified = true;
                    }

                    // Optional : deleting the mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e){
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }
        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return pointBrowserURL;
}
 
Example 19
Source File: MailReader.java    From development with Apache License 2.0 4 votes vote down vote up
public String[] readPassAndKeyFromEmail(boolean delete, String userName)
        throws MessagingException {
    // Download message headers from server.
    int retries = 0;
    String userPass = null;
    String userKey = null;
    while (retries < 40 && userPass == null) {

        // Open main "INBOX" folder.
        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) {
            if (message.getSubject().equals(MAIL_SUBJECT_USER_ACCOUNT_CREATED_EN)) {
                String content = getMessageContent(message);
                String userNameFromEmail = readInformationFromGivenMail(MAIL_BODY_USERNAME_PATTERN_EN, content);
                if (userName.equals(userNameFromEmail)) {
                    userKey = readInformationFromGivenMail(MAIL_BODY_USERKEY_PATTERN_EN, content);
                    userPass = readInformationFromGivenMail(MAIL_BODY_PASSWORD_PATTERN_EN, content);
                    if (delete) {
                        message.setFlag(Flag.DELETED, true);
                    }
                    break;
                }
            }
        }
        folder.close(true);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // ignored
        }
        retries++;
    }

    return new String[] {userKey, userPass};
}
 
Example 20
Source File: EmailUtil.java    From product-es with Apache License 2.0 4 votes vote down vote up
/**
 * This method read e-mails from Gmail inbox and find whether the notification of particular type is found.
 *
 * @param   notificationType    Notification types supported by publisher and store.
 * @return  whether email is found for particular type.
 * @throws  Exception
 */
public static boolean readGmailInboxForNotification(String notificationType) throws Exception {
    boolean isNotificationMailAvailable = false;
    long waitTime = 10000;
    Properties props = new Properties();
    props.load(new FileInputStream(new File(
            TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
                    + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);

    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isNotificationMailAvailable) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if(!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());

                    if (message.getSubject().contains(notificationType)) {
                        isNotificationMailAvailable = true;

                    }
                    // Optional : deleting the  mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e) {
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }

        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return isNotificationMailAvailable;
}