com.icegreen.greenmail.user.UserException Java Examples

The following examples show how to use com.icegreen.greenmail.user.UserException. 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: GreenMailService.java    From greenmail with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #2
Source File: POP3CommandTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void authPlain() throws IOException, MessagingException, UserException {
    try (Socket socket = new Socket(hostAddress, port)) {
        assertThat(socket.isConnected(), is(equalTo(true)));
        PrintStream printStream = new PrintStream(socket.getOutputStream());
        final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // No such user
        assertThat(reader.readLine(), is(startsWith("+OK POP3 GreenMail Server v")));
        printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */);
        assertThat(reader.readLine(), is(equalTo("-ERR Authentication failed: User <test> doesn't exist")));

        greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");

        // Invalid pwd
        printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / <invalid> */);
        assertThat(reader.readLine(), is(equalTo("-ERR Authentication failed: Invalid password")));

        // Successful auth
        printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
        assertThat(reader.readLine(), is(equalTo("+OK")));
    }
}
 
Example #3
Source File: UserCommand.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #4
Source File: Pop3State.java    From greenmail with Apache License 2.0 5 votes vote down vote up
public void authenticate(String pass)
        throws UserException, FolderException {
    if (user == null)
        throw new UserException("No user selected");

    if (manager.isAuthRequired()) {
        user.authenticate(pass);
    }
    inbox = imapHostManager.getInbox(user);
}
 
Example #5
Source File: AuthenticationDisabledTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test(expected = UserException.class)
public void testPop3ConnectAuth() throws MessagingException, UserException, FolderException {
    UserManager userManager = greenMail.getManagers().getUserManager();
    Pop3State status = new Pop3State(userManager);
    userManager.setAuthRequired(true);

    UserImpl user = new UserImpl("[email protected]", "user", "pwd", null);
    status.setUser(user);
    status.authenticate("pass");
}
 
Example #6
Source File: AuthenticationDisabledTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testPop3ConnectNoAuth() throws MessagingException, UserException, FolderException {
    UserManager userManager = greenMail.getManagers().getUserManager();
    Pop3State status = new Pop3State(userManager);
    userManager.setAuthRequired(false);

    UserImpl user = new UserImpl("[email protected]", "user", "pwd", null);
    status.setUser(user);
    status.authenticate("pass");
}
 
Example #7
Source File: Pop3ServerTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testPop3Capabillities() throws MessagingException, UserException {
    final POP3Store store = greenMail.getPop3().createStore();
    greenMail.getManagers().getUserManager().createUser("[email protected]",
            "[email protected]", "pwd");
    store.connect("[email protected]", "pwd");
    try {
        assertTrue(store.capabilities().containsKey("UIDL"));
    } finally {
        store.close();
    }
}
 
Example #8
Source File: POP3CommandTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void authEnabled() throws IOException, UserException {
    try (Socket socket = new Socket(hostAddress, port)) {
        assertThat(socket.isConnected(), is(equalTo(true)));
        PrintStream printStream = new PrintStream(socket.getOutputStream());
        final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        greenMail.getManagers().getUserManager().setAuthRequired(true);

        assertThat(reader.readLine(), is(startsWith("+OK POP3 GreenMail Server v")));
        printStream.print("USER [email protected]" + CRLF);
        assertThat(reader.readLine(), is(not(equalTo("+OK"))));
    }
}
 
Example #9
Source File: POP3CommandTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void authDisabled() throws IOException, UserException {
    try (Socket socket = new Socket(hostAddress, port)) {
        assertThat(socket.isConnected(), is(equalTo(true)));
        PrintStream printStream = new PrintStream(socket.getOutputStream());
        final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        greenMail.getManagers().getUserManager().setAuthRequired(false);

        assertThat(reader.readLine(), is(startsWith("+OK POP3 GreenMail Server v")));
        printStream.print("USER [email protected]" + CRLF);
        assertThat(reader.readLine(), is(equalTo("+OK")));
    }
}
 
Example #10
Source File: POP3CommandTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void authPlainWithContinuation() throws IOException, UserException {
    try (Socket socket = new Socket(hostAddress, port)) {
        assertThat(socket.isConnected(), is(equalTo(true)));
        PrintStream printStream = new PrintStream(socket.getOutputStream());
        final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");

        assertThat(reader.readLine(), is(startsWith("+OK POP3 GreenMail Server v")));
        printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */);
        assertThat(reader.readLine(), is(equalTo(AuthCommand.CONTINUATION)));
        printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
        assertThat(reader.readLine(), is(equalTo("+OK")));
    }
}
 
Example #11
Source File: SMTPCommandTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void authLogin() throws IOException, MessagingException, UserException {
    Session smtpSession = greenMail.getSmtp().createSession();
    SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL);
    try {
        Socket smtpSocket = new Socket(hostAddress, port); // Closed by transport
        smtpTransport.connect(smtpSocket);
        assertThat(smtpTransport.isConnected(), is(equalTo(true)));

        // Should fail, as user does not exist
        smtpTransport.issueCommand("AUTH LOGIN ", 334);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 VXNlciBOYW1lAA==" /* Username */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 UGFzc3dvcmQA" /* Password */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("testpass".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace(AuthCommand.AUTH_CREDENTIALS_INVALID));

        // Try again but create user
        greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");
        smtpTransport.issueCommand("AUTH LOGIN ", 334);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 VXNlciBOYW1lAA==" /* Username */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 UGFzc3dvcmQA" /* Password */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("testpass".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace(AuthCommand.AUTH_SUCCEDED));
    } finally {
        smtpTransport.close();
    }
}
 
Example #12
Source File: ExampleJavaMailTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendAndReceive() throws UnsupportedEncodingException, MessagingException, UserException {
    Session smtpSession = greenMail.getSmtp().createSession();

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

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

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

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

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

    store.close();
    imapStore.close();
}
 
Example #13
Source File: GreenMail.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Override
public GreenMailUser setUser(String email, String login, String password) {
    GreenMailUser user = managers.getUserManager().getUser(login);
    if (null == user) {
        try {
            user = managers.getUserManager().createUser(email, login, password);
        } catch (UserException e) {
            throw new RuntimeException(e);
        }
    } else {
        user.setPassword(password);
    }
    return user;
}
 
Example #14
Source File: Pop3State.java    From greenmail with Apache License 2.0 5 votes vote down vote up
public GreenMailUser findOrCreateUser(String username) throws UserException {
    if (manager.hasUser(username)) {
        return manager.getUser(username);
    }
    if (!manager.isAuthRequired()) {
        return manager.createUser(username, username, username);
    }
    throw new UserException("Unable to find or create user '" + username +"'");
}
 
Example #15
Source File: Pop3State.java    From greenmail with Apache License 2.0 5 votes vote down vote up
public GreenMailUser getUser(String username) throws UserException {
    GreenMailUser user = manager.getUser(username);
    if (null == user) {
        throw new NoSuchUserException("User <" + username + "> doesn't exist");
    }
    return user;
}
 
Example #16
Source File: GreenMailListener.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(final ServletContextEvent sce) {
    log.info("Initializing GreenMail");

    managers = new Managers();
    ServletContext ctx = sce.getServletContext();
    configuration = ConfigurationFactory.create(extractParameters(ctx));
    services = ServiceFactory.create(configuration, managers);

    for (Configuration.User user : configuration.getUsers()) {
        GreenMailUser greenMailUser = managers.getUserManager().getUser(user.email);
        if (null == greenMailUser) {
            try {
                greenMailUser = managers.getUserManager().createUser(
                        user.email, user.login, user.password);
                greenMailUser.setPassword(user.password);
            } catch (UserException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    for (Service s : services) {
        log.info("Starting GreenMail service: {}", s);
        s.startService();
    }

    ContextHelper.initAttributes(ctx, managers, configuration);
}
 
Example #17
Source File: GreenMailClient.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Sending email to the user account in the server with additional headers.
 *
 * @param subject Email subject
 * @throws MessagingException if the properties set to the message are not valid
 * @throws UserException when no such user or user is null
 */
public void sendMail(String subject, Map<String, String> headers)
        throws MessagingException, UserException {
    MimeMessage message = createBasicMessage(subject);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        message.addHeader(entry.getKey(), entry.getValue());
    }
    greenMailUser.deliver(message);
}
 
Example #18
Source File: AlfrescoImapUserManager.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #19
Source File: GreenMailClient.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Sending email to the user account in the server with additional headers.
 *
 * @param subject Email subject
 * @throws MessagingException if the properties set to the message are not valid
 * @throws UserException      when no such user or user is null
 */
public void sendMail(String subject, Map<String, String> headers) throws MessagingException, UserException {
    MimeMessage message = createBasicMessage(subject);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        message.addHeader(entry.getKey(), entry.getValue());
    }
    greenMailUser.deliver(message);
}
 
Example #20
Source File: AlfrescoImapUser.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void deliver(MimeMessage msg) throws UserException
{
    throw new UnsupportedOperationException();
}
 
Example #21
Source File: AlfrescoImapUser.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void deliver(MovingMessage msg) throws UserException
{
    throw new UnsupportedOperationException();
}
 
Example #22
Source File: AlfrescoImapUser.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void delete() throws UserException
{
    throw new UnsupportedOperationException();
}
 
Example #23
Source File: AlfrescoImapUser.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void create() throws UserException
{
    throw new UnsupportedOperationException();
}
 
Example #24
Source File: AlfrescoImapUser.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void authenticate(String password) throws UserException
{
    throw new UnsupportedOperationException();
    // This method is used in the POP3 greenmail implementation, so it is disabled for IMAP
    // See AlfrescoImapUserManager.test() method.
}
 
Example #25
Source File: GreenMailClient.java    From micro-integrator with Apache License 2.0 2 votes vote down vote up
/**
 * Sending email to the user account in the server.
 *
 * @param subject Email subject
 * @throws MessagingException if the properties set to the message are not valid
 * @throws UserException      when no such user or user is null
 */
public void sendMail(String subject) throws MessagingException, UserException {
    MimeMessage message = createBasicMessage(subject);
    greenMailUser.deliver(message);
}
 
Example #26
Source File: GreenMailClient.java    From product-ei with Apache License 2.0 2 votes vote down vote up
/**
 * Sending email to the user account in the server.
 *
 * @param subject Email subject
 * @throws MessagingException if the properties set to the message are not valid
 * @throws UserException when no such user or user is null
 */
public void sendMail(String subject) throws MessagingException, UserException {
    MimeMessage message = createBasicMessage(subject);
    greenMailUser.deliver(message);
}