Java源码示例:com.icegreen.greenmail.user.GreenMailUser

示例1
/**
 * Check mail folder for an email using subject.
 *
 * @param emailSubject Email subject
 * @param folder       mail folder to check for an email
 * @param protocol     protocol used to connect to the server
 * @return whether mail received or not
 * @throws MessagingException if we're unable to connect to the store
 */
private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol,
                                               GreenMailUser user) throws MessagingException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection(user, protocol);
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the Email with Subject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return emailReceived;
}
 
示例2
/**
 * Get the connection to a mail store
 *
 * @param user     whose mail store should be connected
 * @param protocol protocol used to connect
 * @return
 * @throws MessagingException when unable to connect to the store
 */
private static Store getConnection(GreenMailUser user, String protocol) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getInstance(props);
    int port;
    if (PROTOCOL_POP3.equals(protocol)) {
        port = 3110;
    } else if (PROTOCOL_IMAP.equals(protocol)) {
        port = 3143;
    } else {
        port = 3025;
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "localhost");
        props.put("mail.smtp.port", "3025");
    }
    URLName urlName = new URLName(protocol, BIND_ADDRESS, port, null, user.getLogin(), user.getPassword());
    Store store = session.getStore(urlName);
    store.connect();
    return store;
}
 
示例3
/**
 * Check inbox and make sure a particular email is deleted.
 *
 * @param emailSubject Email subject
 * @param protocol     protocol used to connect to the server
 * @return
 * @throws MessagingException   if we're unable to connect to the store
 * @throws InterruptedException if thread sleep fails
 */
public static boolean checkEmailDeleted(String emailSubject, String protocol, GreenMailUser user)
        throws MessagingException, InterruptedException {
    boolean isEmailDeleted = false;
    long startTime = System.currentTimeMillis();

    while ((System.currentTimeMillis() - startTime) < WAIT_TIME_MS) {
        if (!isMailReceivedBySubject(emailSubject, EMAIL_INBOX, protocol, user)) {
            log.info("Email has been deleted successfully!");
            isEmailDeleted = true;
            break;
        }
        Thread.sleep(500);
    }
    return isEmailDeleted;
}
 
示例4
/**
 * Check whether email received by reading the emails.
 *
 * @param protocol to connect to the store
 * @param user     whose mail store should be connected
 * @param subject  the subject of the mail to search
 * @return
 * @throws MessagingException when unable to connect to the store
 */
public static boolean isMailReceived(String protocol, GreenMailUser user, String subject)
        throws MessagingException {
    Store store = getConnection(user, protocol);
    Folder folder = store.getFolder(EMAIL_INBOX);
    folder.open(Folder.READ_ONLY);
    boolean isReceived = false;
    Message[] messages = folder.getMessages();
    for (Message message : messages) {
        if (message.getSubject().contains(subject)) {
            log.info("Found the Email with Subject : " + subject);
            isReceived = true;
            break;
        }
    }
    return isReceived;
}
 
示例5
public GreenMailUser getUserByEmail(String email)
{
    GreenMailUser ret = getUser(email);
    if (null == ret)
    {
        for (GreenMailUser user : userMap.values())
        {
            // TODO: NPE!
            if (user.getEmail().trim().equalsIgnoreCase(email.trim()))
            {
                return user;
            }
        }
    }
    return ret;
}
 
示例6
/**
 * The login method.
 * 
 */
public boolean test(String userid, String password)
{
    try
    {
        authenticationService.authenticate(userid, password.toCharArray());
        String email = null;
        if (personService.personExists(userid))
        {
            NodeRef personNodeRef = personService.getPerson(userid);
            email = (String) nodeService.getProperty(personNodeRef, ContentModel.PROP_EMAIL);
        }
        GreenMailUser user = new AlfrescoImapUser(email, userid, password);
        addUser(user);
    }
    catch (AuthenticationException ex)
    {
        logger.error("IMAP authentication failed for userid: " + userid);
        return false;
    }
    return true;
}
 
示例7
/**
 * Returns an collection of subscribed mailboxes. To appear in search result mailboxes should have
 * {http://www.alfresco.org/model/imap/1.0}subscribed property specified for user. Method searches
 * subscribed mailboxes under mount points defined for a specific user. Mount points include user's
 * IMAP Virtualised Views and Email Archive Views. This method serves LSUB command of the IMAP protocol.
 * 
 * @param user User making the request
 * @param mailboxPattern String name of a mailbox possible including a wildcard.
 * @return Collection of mailboxes matching the pattern.
 * @throws com.icegreen.greenmail.store.FolderException
 */
public Collection<MailFolder> listSubscribedMailboxes(GreenMailUser user, String mailboxPattern)
        throws FolderException
{
    try
    {
        AlfrescoImapUser alfrescoUser = new AlfrescoImapUser(user.getEmail(), user.getLogin(), user.getPassword());
        return registerMailboxes(imapService.listMailboxes(alfrescoUser, getUnqualifiedMailboxPattern(
                alfrescoUser, mailboxPattern), true));
    }
    catch (Throwable e)
    {
        logger.debug(e.getMessage(), e);
        throw new FolderException(e.getMessage());
    }
}
 
示例8
/**
 * Renames an existing mailbox. The specified mailbox must already exist, the requested name must not exist
 * already but must be able to be created and the user must have rights to delete the existing mailbox and
 * create a mailbox with the new name. Any inferior hierarchical names must also be renamed. If INBOX is renamed,
 * the contents of INBOX are transferred to a new mailbox with the new name, but INBOX is not deleted.
 * If INBOX has inferior mailbox these are not renamed. This method serves RENAME command of the IMAP
 * protocol. <p/> Method searches mailbox under mount points defined for a specific user. Mount points
 * include user's IMAP Virtualised Views and Email Archive Views.
 * 
 * @param user User making the request.
 * @param oldMailboxName String name of the existing folder
 * @param newMailboxName String target new name
 * @throws com.icegreen.greenmail.store.FolderException if an existing folder with the new name.
 * @throws AlfrescoImapFolderException if user does not have rights to create the new mailbox.
 */
public void renameMailbox(GreenMailUser user, String oldMailboxName, String newMailboxName) throws FolderException, AuthorizationException
{
    try
    {
        AlfrescoImapUser alfrescoUser = new AlfrescoImapUser(user.getEmail(), user.getLogin(), user.getPassword());
        String oldFolderPath = getUnqualifiedMailboxPattern(alfrescoUser,
                oldMailboxName);
        String newFolderpath = getUnqualifiedMailboxPattern(alfrescoUser, newMailboxName);
        imapService.renameMailbox(alfrescoUser, oldFolderPath, newFolderpath);
        if (folderCache != null)
        {
            folderCache.remove(oldFolderPath);
            folderCache.remove(newFolderpath);
        }
    }
    catch (Throwable e)
    {
        logger.debug(e.getMessage(), e);
        throw new FolderException(e.getMessage());
    }
}
 
示例9
/**
 * Deletes an existing MailBox. Specified mailbox must already exist on this server, and the user
 * must have rights to delete it. <p/> This method serves DELETE command of the IMAP protocol.
 * 
 * @param user User making the request.
 * @param mailboxName String name of the target
 * @throws com.icegreen.greenmail.store.FolderException if mailbox has a non-selectable store with children
 */
public void deleteMailbox(GreenMailUser user, String mailboxName) throws FolderException, AuthorizationException
{
    try
    {
        AlfrescoImapUser alfrescoUser = new AlfrescoImapUser(user.getEmail(), user.getLogin(), user.getPassword());
        String folderPath = getUnqualifiedMailboxPattern(alfrescoUser, mailboxName);
        imapService.deleteMailbox(alfrescoUser, folderPath);
        if (folderCache != null)
        {
            folderCache.remove(folderPath);
        }
    }
    catch (Throwable e)
    {
        logger.debug(e.getMessage(), e);
        throw new FolderException(e.getMessage());
    }
}
 
示例10
/**
 * Returns a reference to an existing Mailbox. The requested mailbox must already exists on this server and the
 * requesting user must have at least lookup rights. <p/> It is also can be used by to obtain hierarchy delimiter
 * by the LIST command: <p/> C: 2 list "" "" <p/> S: * LIST () "." "" <p/> S: 2 OK LIST completed.
 * <p/>
 * Method searches mailbox under mount points defined for a specific user. Mount points include user's IMAP
 * Virtualised Views and Email Archive Views.
 * 
 * @param user User making the request.
 * @param mailboxName String name of the target.
 * @return an Mailbox reference.
 */
public MailFolder getFolder(GreenMailUser user, String mailboxName)
{
    AlfrescoImapUser alfrescoUser = new AlfrescoImapUser(user.getEmail(), user.getLogin(), user.getPassword());
    String folderPath = getUnqualifiedMailboxPattern(
            alfrescoUser, mailboxName);

    if (folderCache == null)
    {
        registerMailBox(imapService.getOrCreateMailbox(alfrescoUser, mailboxName, true, false));
    }

    AlfrescoImapFolder result = folderCache.get(folderPath);

    // if folder isn't in cache then add it via registerMailBox method
    return result != null ? result : registerMailBox(imapService.getOrCreateMailbox(alfrescoUser, mailboxName, true, false));
}
 
示例11
/**
 * Simply calls {@link #getFolder(GreenMailUser, String)}. <p/> Added to implement {@link ImapHostManager}.
 */
public MailFolder getFolder(final GreenMailUser user, final String mailboxName, boolean mustExist)
        throws FolderException
{
    try
    {
        return getFolder(user, mailboxName);
    }
    catch (AlfrescoImapRuntimeException e)
    {
        if (!mustExist)
        {
            return null;
        }
        else if (e.getCause() instanceof FolderException)
        {
            throw (FolderException) e.getCause();
        }
        throw e;
    }
}
 
示例12
private void addMailUser(final String user) {
    // Parse ...
    int posColon = user.indexOf(':');
    int posAt = user.indexOf('@');
    String login = user.substring(0, posColon);
    String pwd = user.substring(posColon + 1, posAt);
    String domain = user.substring(posAt + 1);
    String email = login + '@' + domain;
    if (log.isDebugEnabled()) {
        // This is a test system, so we do not care about pwd in the log file.
        log.debug("Adding user " + login + ':' + pwd + '@' + domain);
    }


    GreenMailUser greenMailUser = managers.getUserManager().getUser(email);
    if (null == greenMailUser) {
        try {
            greenMailUser = managers.getUserManager().createUser(email, login, pwd);
            greenMailUser.setPassword(pwd);
        } catch (UserException e) {
            throw new RuntimeException(e);
        }
    }
}
 
示例13
public void deliverMultipartMessage(String user, String password, String from, String subject,
                                                                   String contentType, Object body) throws Exception {
    GreenMailUser greenUser = greenMail.setUser(user, password);
    MimeMultipart multiPart = new MimeMultipart();
    MimeBodyPart textPart = new MimeBodyPart();
    multiPart.addBodyPart(textPart);
    textPart.setContent(body, contentType);

    Session session = GreenMailUtil.getSession(server.getServerSetup());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setRecipients(Message.RecipientType.TO, greenUser.getEmail());
    mimeMessage.setFrom(from);
    mimeMessage.setSubject(subject);
    mimeMessage.setContent(multiPart, "multipart/mixed");
    greenUser.deliver(mimeMessage);
}
 
示例14
/**
 * Get the connection to a mail store
 *
 * @param user     whose mail store should be connected
 * @param protocol protocol used to connect
 * @return
 * @throws MessagingException when unable to connect to the store
 */
private static Store getConnection(GreenMailUser user, String protocol) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getInstance(props);
    int port;
    if (PROTOCOL_POP3.equals(protocol)) {
        port = 3110;
    } else if (PROTOCOL_IMAP.equals(protocol)) {
        port = 3143;
    } else {
        port = 3025;
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "localhost");
        props.put("mail.smtp.port", "3025");
    }
    URLName urlName = new URLName(protocol, BIND_ADDRESS, port, null, user.getLogin(), user.getPassword());
    Store store = session.getStore(urlName);
    store.connect();
    return store;
}
 
示例15
/**
 * Check mail folder for an email using subject.
 *
 * @param emailSubject Email subject
 * @param folder       mail folder to check for an email
 * @param protocol     protocol used to connect to the server
 * @return whether mail received or not
 * @throws MessagingException if we're unable to connect to the store
 */
private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol,
        GreenMailUser user) throws MessagingException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection(user, protocol);
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the Email with Subject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return emailReceived;
}
 
示例16
/**
 * Check inbox and make sure a particular email is deleted.
 *
 * @param emailSubject Email subject
 * @param protocol     protocol used to connect to the server
 * @return
 * @throws MessagingException if we're unable to connect to the store
 * @throws InterruptedException if thread sleep fails
 */
public static boolean checkEmailDeleted(String emailSubject, String protocol, GreenMailUser user)
        throws MessagingException, InterruptedException {
    boolean isEmailDeleted = false;
    long startTime = System.currentTimeMillis();

    while ((System.currentTimeMillis() - startTime) < WAIT_TIME_MS) {
        if (!isMailReceivedBySubject(emailSubject, EMAIL_INBOX, protocol, user)) {
            log.info("Email has been deleted successfully!");
            isEmailDeleted = true;
            break;
        }
        Thread.sleep(500);
    }
    return isEmailDeleted;
}
 
示例17
/**
 * Check whether email received by reading the emails.
 *
 * @param protocol to connect to the store
 * @param user whose mail store should be connected
 * @param subject the subject of the mail to search
 * @return
 * @throws MessagingException when unable to connect to the store
 */
public static boolean isMailReceived(String protocol, GreenMailUser user, String subject)
        throws MessagingException {
    Store store = getConnection(user, protocol);
    Folder folder = store.getFolder(EMAIL_INBOX);
    folder.open(Folder.READ_ONLY);
    boolean isReceived = false;
    Message[] messages = folder.getMessages();
    for (Message message : messages) {
        if (message.getSubject().contains(subject)) {
            log.info("Found the Email with Subject : " + subject);
            isReceived = true;
            break;
        }
    }
    return isReceived;
}
 
示例18
@Test
public void testReceive() throws MessagingException, IOException {
    //Start all email servers using non-default ports.
    GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP);
    try {
        greenMail.start();

        //Use random content to avoid potential residual lingering problems
        final String subject = GreenMailUtil.random();
        final String body = GreenMailUtil.random();
        MimeMessage message = createMimeMessage(subject, body, greenMail); // Construct message
        GreenMailUser user = greenMail.setUser("[email protected]", "waelc", "soooosecret");
        user.deliver(message);
        assertEquals(1, greenMail.getReceivedMessages().length);

        // --- Place your retrieve code here

    } finally {
        greenMail.stop();
    }
}
 
示例19
private void handle(MovingMessage msg, MailAddress mailAddress) {
    try {
        GreenMailUser user = userManager.getUserByEmail(mailAddress.getEmail());
        if (null == user) {
            String login = mailAddress.getEmail();
            String email = mailAddress.getEmail();
            String password = mailAddress.getEmail();
            user = userManager.createUser(email, login, password);
            log.info("Created user login {} for address {} with password {} because it didn't exist before.",
                    login, email, password);
        }

        user.deliver(msg);
    } catch (Exception e) {
        throw new IllegalStateException("Can not deliver message " + msg + " to " + mailAddress, e);
    }

    msg.releaseContent();
}
 
示例20
/**
 * @see CommandTemplate#doProcess
 */
@Override
protected void doProcess(ImapRequestLineReader request,
                         ImapResponse response,
                         ImapSession session)
        throws ProtocolException {
    String userid = parser.astring(request);
    String password = parser.astring(request);
    parser.endLine(request);

    if (session.getUserManager().test(userid, password)) {
        GreenMailUser user = session.getUserManager().getUser(userid);
        session.setAuthenticated(user);
        response.commandComplete(this);

    } else {
        response.commandFailed(this, "Invalid login/password for user id "+userid);
    }
}
 
示例21
/**
 * @see ImapHostManager#deleteMailbox
 */
@Override
public void deleteMailbox(GreenMailUser user, String mailboxName)
        throws FolderException, AuthorizationException {
    MailFolder toDelete = getFolder(user, mailboxName, true);
    if (store.getChildren(toDelete).isEmpty()) {
        toDelete.deleteAllMessages();
        toDelete.signalDeletion();
        store.deleteMailbox(toDelete);
    } else {
        if (toDelete.isSelectable()) {
            toDelete.deleteAllMessages();
            store.setSelectable(toDelete, false);
        } else {
            throw new FolderException("Can't delete a non-selectable store with children.");
        }
    }
}
 
示例22
/**
 * Partial implementation of list functionality.
 * TODO: Handle wildcards anywhere in store pattern
 * (currently only supported as last character of pattern)
 *
 * @see com.icegreen.greenmail.imap.ImapHostManager#listMailboxes
 */
private Collection<MailFolder> listMailboxes(GreenMailUser user,
                                 String mailboxPattern,
                                 boolean subscribedOnly)
        throws FolderException {
    List<MailFolder> mailboxes = new ArrayList<>();
    String qualifiedPattern = getQualifiedMailboxName(user, mailboxPattern);

    for (MailFolder folder : store.listMailboxes(qualifiedPattern)) {
        // TODO check subscriptions.
        if (subscribedOnly && !subscriptions.isSubscribed(user, folder)) {
            // if not subscribed
            folder = null;
        }

        // Sets the store to null if it's not viewable.
        folder = checkViewable(folder);

        if (folder != null) {
            mailboxes.add(folder);
        }
    }

    return mailboxes;
}
 
示例23
/**
 * Convert a user specified store name into a server absolute name.
 * If the mailboxName begins with the namespace token,
 * return as-is.
 * If not, need to resolve the Mailbox name for this user.
 * Example:
 * <br> Convert "INBOX" for user "Fred.Flinstone" into
 * absolute name: "#user.Fred.Flintstone.INBOX"
 *
 * @return String of absoluteName, null if not valid selection
 */
private String getQualifiedMailboxName(GreenMailUser user, String mailboxName) {
    String userNamespace = user.getQualifiedMailboxName();

    if ("INBOX".equalsIgnoreCase(mailboxName)) {
        return USER_NAMESPACE + HIERARCHY_DELIMITER + userNamespace +
                HIERARCHY_DELIMITER + INBOX_NAME;
    }

    if (mailboxName.startsWith(NAMESPACE_PREFIX)) {
        return mailboxName;
    } else {
        if (mailboxName.length() == 0) {
            return USER_NAMESPACE + HIERARCHY_DELIMITER + userNamespace;
        } else {
            return USER_NAMESPACE + HIERARCHY_DELIMITER + userNamespace +
                    HIERARCHY_DELIMITER + mailboxName;
        }
    }
}
 
示例24
/**
 * Sets a quota for a users.
 *
 * @param user  the user.
 * @param quota the quota.
 */
public static void setQuota(final GreenMailUser user, final Quota quota) {
    Session session = GreenMailUtil.getSession(ServerSetupTest.IMAP);
    try {
        Store store = session.getStore("imap");
        store.connect(user.getEmail(), user.getPassword());
        try {
            ((QuotaAwareStore) store).setQuota(quota);
        } finally {
            store.close();
        }
    } catch (Exception ex) {
        throw new IllegalStateException("Can not set quota " + quota
                + " for user " + user, ex);
    }
}
 
示例25
private void testSubject(String subject) throws Exception {
    GreenMailUser user = greenMail.setUser("[email protected]", "pwd");
    assertNotNull(greenMail.getImap());

    MailFolder folder = greenMail.getManagers().getImapHostManager().getFolder(user, "INBOX");
    storeSearchTestMessages(greenMail.getImap().createSession(), folder, subject);

    greenMail.waitForIncomingEmail(1);

    final Store store = greenMail.getImap().createStore();
    store.connect("[email protected]", "pwd");
    try {
        Folder imapFolder = store.getFolder("INBOX");
        imapFolder.open(Folder.READ_ONLY);

        Message[] imapMessages = imapFolder.getMessages();
        assertTrue(null != imapMessages && imapMessages.length == 1);
        Message imapMessage = imapMessages[0];
        assertEquals(subject.replaceAll("\\s+",""), imapMessage.getSubject().replaceAll("\\s+",""));
    } finally {
        store.close();
    }
}
 
示例26
@Override
public void execute(Pop3Connection conn, Pop3State state,
                    String cmd) {
    GreenMailUser user = state.getUser();
    if (user == null) {
        conn.println("-ERR USER required");

        return;
    }

    String[] args = cmd.split(" ");
    if (args.length < 2) {
        conn.println("-ERR Required syntax: PASS <username>");

        return;
    }

    try {
        String pass = args[1];
        state.authenticate(pass);
        conn.println("+OK");
    } catch (Exception e) {
        conn.println("-ERR Authentication failed: " + e);
    }
}
 
示例27
@Override
public void execute(Pop3Connection conn, Pop3State state,
                    String cmd) {
    try {
        String[] args = cmd.split(" ");
        if (args.length < 2) {
            conn.println("-ERR Required syntax: USER <username>");
            return;
        }

        String username = args[1];
        GreenMailUser user = state.findOrCreateUser(username);
        if (null == user) {
            conn.println("-ERR User '" + username + "' not found");
            return;
        }
        state.setUser(user);
        conn.println("+OK");
    } catch (UserException nsue) {
        conn.println("-ERR " + nsue);
    }
}
 
示例28
/**
 * Check trash and make sure a particular email is moved to trash.
 *
 * @param emailSubject Email subject
 * @param protocol     protocol used to connect to the server
 * @return
 * @throws MessagingException   if we're unable to connect to the store
 * @throws InterruptedException if thread sleep fails
 */
public static boolean checkEmailMoved(String emailSubject, String protocol, GreenMailUser user)
        throws MessagingException, InterruptedException {
    boolean mailReceived = false;
    long startTime = System.currentTimeMillis();
    while ((System.currentTimeMillis() - startTime) < WAIT_TIME_MS) {
        if (isMailReceivedBySubject(emailSubject, EMAIL_TRASH, protocol, user)) {
            log.info("Found the moved email in mailbox : " + emailSubject);
            mailReceived = true;
            break;
        }
        Thread.sleep(500);
    }
    return mailReceived;
}
 
示例29
public void addMessage(String testName, GreenMailUser user) throws MessagingException {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("[email protected]"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
    message.setSubject("Test email" + testName);
    message.setText("test test test chocolate");
    user.deliver(message);
}
 
示例30
public GreenMailUser createUser(String email, String login, String password) throws UserException
{
    // TODO: User creation/addition code should be implemented here (in the AlfrescoImapUserManager).
    // Following code is not need and not used in the current implementation.
    GreenMailUser user = new AlfrescoImapUser(email, login, password);
    user.create();
    addUser(user);
    return user;
}