@Before
  public void prepare() throws Exception {
    String[] springConfigFiles = {
      "account-email.xml", "account-persist.xml", "account-captcha.xml", "account-service.xml"
    };

    ApplicationContext ctx = new ClassPathXmlApplicationContext(springConfigFiles);

    AccountCaptchaService accountCaptchaService =
        (AccountCaptchaService) ctx.getBean("accountCaptchaService");

    List<String> preDefinedTexts = new ArrayList<String>();
    preDefinedTexts.add("12345");
    preDefinedTexts.add("abcde");
    accountCaptchaService.setPreDefinedTexts(preDefinedTexts);

    accountService = (AccountService) ctx.getBean("accountService");

    greenMail = new GreenMail(ServerSetup.SMTP);
    greenMail.setUser("*****@*****.**", "123456");
    greenMail.start();

    File persistDataFile = new File("target/test-classes/persist-data.xml");
    if (persistDataFile.exists()) {
      persistDataFile.delete();
    }
  }
  // http://jira.qos.ch/browse/LBCLASSIC-221
  @Test
  public void bufferShouldBeResetBetweenMessages() throws Exception {
    buildSMTPAppender(smtpServer.getSmtp().getPort(), SYNCHRONOUS);
    smtpAppender.setLayout(buildPatternLayout(lc, DEFAULT_PATTERN));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    String msg0 = "hello zero";
    logger.debug(msg0);
    logger.error("error zero");

    String msg1 = "hello one";
    logger.debug(msg1);
    logger.error("error one");

    waitUntilEmailIsSent();
    waitUntilEmailIsReceived(smtpServer, 2);

    MimeMessage[] mma = smtpServer.getReceivedMessages();
    assertNotNull(mma);
    assertEquals(2, mma.length);

    MimeMessage mm0 = mma[0];
    MimeMultipart content0 = (MimeMultipart) mm0.getContent();
    String body0 = GreenMailUtil.getBody(content0.getBodyPart(0));
    assertTrue(body0.contains(msg0));

    MimeMessage mm1 = mma[1];
    MimeMultipart content1 = (MimeMultipart) mm1.getContent();
    String body1 = GreenMailUtil.getBody(content1.getBodyPart(0));
    // second body should not contain content from first message
    assertFalse(body1.contains(msg0));
  }
Пример #3
0
  @Test
  public void sendSimpleMail() throws MessagingException, InterruptedException, IOException {
    simpleMailService.sendNotificationMail("calvin");

    greenMail.waitForIncomingEmail(2000, 1);

    MimeMessage[] messages = greenMail.getReceivedMessages();
    MimeMessage message = messages[messages.length - 1];

    assertEquals("*****@*****.**", message.getFrom()[0].toString());
    assertEquals("用户修改通知", message.getSubject());
    // text格式内容
    System.out.println(message.getContent());
    assertTrue(((String) message.getContent()).contains("被修改"));
  }
Пример #4
0
  @Override
  public void setUp() throws Exception {
    ServerSocket socket = new ServerSocket(0);
    this.emailServerPort = socket.getLocalPort();
    socket.close();

    // ServerSetup smtp = new ServerSetup( 1234, null, ServerSetup.PROTOCOL_SMTP );
    ServerSetup smtp = new ServerSetup(this.emailServerPort, null, ServerSetup.PROTOCOL_SMTP);

    server = new GreenMail(smtp);
    server.setUser("*****@*****.**", "smtp-username", "smtp-password");
    server.start();

    this.lookup(SecuritySystem.class).start();
  }
  @Test
  public void testMultipleTo() throws Exception {
    buildSMTPAppender(smtpServer.getSmtp().getPort(), SYNCHRONOUS);
    smtpAppender.setLayout(buildPatternLayout(lc, DEFAULT_PATTERN));
    smtpAppender.addTo("Test <*****@*****.**>, [email protected]");
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("hello");
    logger.error("an error", new Exception("an exception"));

    waitUntilEmailIsReceived(smtpServer, 3);
    MimeMessage[] mma = smtpServer.getReceivedMessages();
    assertNotNull(mma);
    assertEquals(3, mma.length);
  }
  // http://jira.qos.ch/browse/LBCLASSIC-221
  @Test
  public void bufferShouldBeResetBetweenMessages() throws Exception {
    buildSMTPAppender("bufferShouldBeResetBetweenMessages", SYNCHRONOUS);
    smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    String msg0 = "hello zero";
    logger.debug(msg0);
    logger.error("error zero");

    String msg1 = "hello one";
    logger.debug(msg1);
    logger.error("error one");

    Thread.yield();
    int oldCount = 0;
    int expectedEmailCount = oldCount + 2;
    waitForServerToReceiveEmails(expectedEmailCount);

    MimeMessage[] mma = greenMailServer.getReceivedMessages();
    assertNotNull(mma);
    assertEquals(expectedEmailCount, mma.length);

    MimeMessage mm0 = mma[oldCount];
    MimeMultipart content0 = (MimeMultipart) mm0.getContent();
    String body0 = GreenMailUtil.getBody(content0.getBodyPart(0));

    MimeMessage mm1 = mma[oldCount + 1];
    MimeMultipart content1 = (MimeMultipart) mm1.getContent();
    String body1 = GreenMailUtil.getBody(content1.getBodyPart(0));
    // second body should not contain content from first message
    assertFalse(body1.contains(msg0));
  }
Пример #7
0
  @Override
  protected void before() throws Throwable {
    ServerSetup setup = new ServerSetup(3025, "localhost", "smtp");

    greenMail = new GreenMail(setup);
    greenMail.start();
  }
  @Test
  public void testAccountService() throws Exception {
    // 1. Get captcha
    String captchaKey = accountService.generateCaptchaKey();
    accountService.generateCaptchaImage(captchaKey);
    String captchaValue = "12345";

    // 2. Submit sign up Request
    SignUpRequest signUpRequest = new SignUpRequest();
    signUpRequest.setCaptchaKey(captchaKey);
    signUpRequest.setCaptchaValue(captchaValue);
    signUpRequest.setId("juven");
    signUpRequest.setEmail("*****@*****.**");
    signUpRequest.setName("Juven Xu");
    signUpRequest.setPassword("admin123");
    signUpRequest.setConfirmPassword("admin123");
    signUpRequest.setActivateServiceUrl("http://localhost:8080/account/activate");
    accountService.signUp(signUpRequest);

    // 3. Read activation link
    greenMail.waitForIncomingEmail(2000, 1);
    Message[] msgs = greenMail.getReceivedMessages();
    assertEquals(1, msgs.length);
    assertEquals("Please Activate Your Account", msgs[0].getSubject());
    String activationLink = GreenMailUtil.getBody(msgs[0]).trim();

    // 3a. Try login but not activated
    try {
      accountService.login("juven", "admin123");
      fail("Disabled account shouldn't be able to log in.");
    } catch (AccountServiceException e) {
    }

    // 4. Activate account
    String activationCode = activationLink.substring(activationLink.lastIndexOf("=") + 1);
    accountService.activate(activationCode);

    // 5. Login with correct id and password
    accountService.login("juven", "admin123");

    // 5a. Login with incorrect password
    try {
      accountService.login("juven", "admin456");
      fail("Password is incorrect, shouldn't be able to login.");
    } catch (AccountServiceException e) {
    }
  }
Пример #9
0
 @Before
 public void setUp() {
   beforeTest = new Date();
   greenMail.start();
   mailbox = "*****@*****.**";
   password = "******";
   greenMail.setUser(mailbox, password);
   udr =
       new UserDataRequest(
           new Credentials(User.Factory.create().createUser(mailbox, mailbox, null), password),
           null,
           null,
           null);
   testUtils =
       new ImapTestUtils(
           mailboxService, privateMailboxService, udr, mailbox, beforeTest, collectionPathHelper);
 }
Пример #10
0
  public StubMailServer() {

    greenmail = new GreenMail(new ServerSetup[] {IMAP_SERVER_SETUP, SMTP_SERVER_SETUP});
    GreenMailUser user =
        greenmail.setUser(
            UserForImap.TEST_USER.emailAddress,
            UserForImap.TEST_USER.loginUsername,
            UserForImap.TEST_USER.password);

    for (String mailbox : new String[] {"Drafts", "Spam"}) {
      Log.d(K9.LOG_TAG, "creating mailbox " + mailbox);
      try {
        greenmail.getManagers().getImapHostManager().createMailbox(user, mailbox);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    greenmail.start();
  }
 private MimeMultipart verify(GreenMail testServer, String subject)
     throws MessagingException, IOException, InterruptedException {
   waitUntilEmailIsReceived(testServer, 1);
   MimeMessage[] mma = testServer.getReceivedMessages();
   assertNotNull(mma);
   assertEquals(1, mma.length);
   MimeMessage mm = mma[0];
   // http://jira.qos.ch/browse/LBCLASSIC-67
   assertEquals(subject, mm.getSubject());
   return (MimeMultipart) mm.getContent();
 }
 @Before
 public void setUp() throws Exception {
   MDC.clear();
   ServerSetup serverSetup = new ServerSetup(port, "localhost", ServerSetup.PROTOCOL_SMTP);
   greenMailServer = new GreenMail(serverSetup);
   greenMailServer.start();
   // give the server a head start
   if (EnvUtilForTests.isRunningOnSlowJenkins()) {
     Thread.sleep(2000);
   } else {
     Thread.sleep(50);
   }
 }
 private MimeMultipart verifyAndExtractMimeMultipart(String subject)
     throws MessagingException, IOException, InterruptedException {
   int oldCount = 0;
   int expectedEmailCount = 1;
   // wait for the server to receive the messages
   waitForServerToReceiveEmails(expectedEmailCount);
   MimeMessage[] mma = greenMailServer.getReceivedMessages();
   assertNotNull(mma);
   assertEquals(expectedEmailCount, mma.length);
   MimeMessage mm = mma[oldCount];
   // http://jira.qos.ch/browse/LBCLASSIC-67
   assertEquals(subject, mm.getSubject());
   return (MimeMultipart) mm.getContent();
 }
Пример #14
0
  @Test
  public void testRestPassword() throws Exception {

    this.copyDefaultConfigToPlace();
    this.setupEmailConfig();

    NexusConfiguration nexusConfig = this.lookup(NexusConfiguration.class);
    nexusConfig.loadConfiguration(true);

    String username = "******";

    PlexusResource resetEmailPR = this.lookup(PlexusResource.class, "UserResetPlexusResource");

    Request request = new Request();
    Response response = new Response(request);
    request.getAttributes().put(UserResetPlexusResource.USER_ID_KEY, username);
    resetEmailPR.delete(null, request, response);

    // Need 1 message
    server.waitForIncomingEmail(5000, 1);

    MimeMessage[] msgs = server.getReceivedMessages();
    Assert.assertTrue("Expected email.", msgs != null && msgs.length > 0);
    MimeMessage msg = msgs[0];

    String password = null;
    // Sample body: Your password has been reset. Your new password is: c1r6g4p8l7
    String body = GreenMailUtil.getBody(msg);

    int index = body.indexOf("Your new password is: ");
    int passwordStartIndex = index + "Your new password is: ".length();
    if (index != -1) {
      password = body.substring(passwordStartIndex, body.indexOf('\n', passwordStartIndex)).trim();
    }

    Assert.assertNotNull(password);
  }
Пример #15
0
  @Test
  public void sendMimeMail() throws InterruptedException, MessagingException, IOException {
    mimeMailService.sendNotificationMail("calvin");

    greenMail.waitForIncomingEmail(2000, 1);
    MimeMessage[] messages = greenMail.getReceivedMessages();
    MimeMessage message = messages[messages.length - 1];

    assertEquals("*****@*****.**", message.getFrom()[0].toString());
    assertEquals("用户修改通知", message.getSubject());

    MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();

    assertEquals(2, mimeMultipart.getCount());

    // Html格式的主邮件
    String mainPartText = getMainPartText(mimeMultipart.getBodyPart(0));
    System.out.println(mainPartText);
    assertTrue(mainPartText.contains("<h1>用户calvin被修改.</h1>"));

    // 附件
    assertEquals(
        "Hello,i am a attachment.", GreenMailUtil.getBody(mimeMultipart.getBodyPart(1)).trim());
  }
  @Test
  public void asyncronousSmoke() throws Exception {
    buildSMTPAppender(smtpServer.getSmtp().getPort(), ASYNCHRONOUS);
    smtpAppender.setLayout(buildPatternLayout(lc, DEFAULT_PATTERN));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("hello");
    logger.error("an error", new Exception("an exception"));

    waitUntilEmailIsSent();
    MimeMultipart mp = verify(smtpServer, TEST_SUBJECT);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertTrue(body.startsWith(HEADER.trim()));
    assertTrue(body.endsWith(FOOTER.trim()));
  }
  // See also http://jira.qos.ch/browse/LOGBACK-734
  @Test
  public void callerDataShouldBeCorrectlySetWithAsyncronousSending() throws Exception {
    buildSMTPAppender(smtpServer.getSmtp().getPort(), ASYNCHRONOUS);
    smtpAppender.setLayout(buildPatternLayout(lc, DEFAULT_PATTERN));
    smtpAppender.setIncludeCallerData(true);
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("hello");
    logger.error("an error", new Exception("an exception"));

    waitUntilEmailIsSent();
    MimeMultipart mp = verify(smtpServer, TEST_SUBJECT);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertTrue(body.contains("DEBUG " + this.getClass().getName() + " - hello"));
  }
  @Before
  public void setUp() throws Exception {

    OnConsoleStatusListener.addNewInstanceToContext(loggerContext);
    MDC.clear();
    ServerSetup serverSetup = new ServerSetup(port, "localhost", ServerSetup.PROTOCOL_SMTP);
    greenMailServer = new GreenMail(serverSetup);
    greenMailServer.start();
    // give the server a head start
    if (EnvUtilForTests.isRunningOnSlowJenkins()) {
      Thread.sleep(2000);
    } else {
      Thread.sleep(50);
    }
  }
  @Test
  public void testCustomBufferSize() throws Exception {
    configure(
        smtpServer.getSmtp().getPort(),
        ClassicTestConstants.JORAN_INPUT_PREFIX + "smtp/customBufferSize.xml");

    logger.debug("invisible1");
    logger.debug("invisible2");
    String msg = "hello";
    logger.error(msg);
    waitUntilEmailIsSent();
    MimeMultipart mp = verify(smtpServer, this.getClass().getName() + " - " + msg);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertEquals(msg, body);
  }
  @Test
  public void testCustomEvaluator() throws Exception {
    configure(
        greenMailServer.getSmtp().getPort(),
        ClassicTestConstants.JORAN_INPUT_PREFIX + "smtp/customEvaluator.xml");

    logger.debug("test");
    String msg2 = "CustomEvaluator";
    logger.debug(msg2);
    logger.debug("invisible");
    waitUntilEmailIsSent();
    MimeMultipart mp =
        verifyAndExtractMimeMultipart(
            "testCustomEvaluator " + this.getClass().getName() + " - " + msg2);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertEquals("testCustomEvaluator", body);
  }
 // this test fails intermittently on Jenkins.
 @Test
 public void testMultipleTo() throws Exception {
   buildSMTPAppender("testMultipleTo", SYNCHRONOUS);
   smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN));
   // buildSMTPAppender() already added one destination address
   smtpAppender.addTo("Test <*****@*****.**>, [email protected]");
   smtpAppender.start();
   logger.addAppender(smtpAppender);
   logger.debug("testMultipleTo hello");
   logger.error("testMultipleTo en error", new Exception("an exception"));
   Thread.yield();
   int expectedEmailCount = 3;
   waitForServerToReceiveEmails(expectedEmailCount);
   MimeMessage[] mma = greenMailServer.getReceivedMessages();
   assertNotNull(mma);
   assertEquals(expectedEmailCount, mma.length);
 }
  @Test
  public void LBCLASSIC_104() throws Exception {
    buildSMTPAppender(smtpServer.getSmtp().getPort(), SYNCHRONOUS);
    smtpAppender.setAsynchronousSending(false);
    smtpAppender.setLayout(buildPatternLayout(lc, DEFAULT_PATTERN));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    MDC.put("key", "val");
    logger.debug("hello");
    MDC.clear();
    logger.error("an error", new Exception("an exception"));

    MimeMultipart mp = verify(smtpServer, TEST_SUBJECT);
    String body = GreenMailUtil.getBody(mp.getBodyPart(0));
    assertTrue("missing HEADER in body", body.startsWith(HEADER.trim()));
    assertTrue("missing MDC in body", body.contains("key=val"));
    assertTrue("missing FOOTER in body", body.endsWith(FOOTER.trim()));
  }
  @Test
  public void html() throws Exception {
    buildSMTPAppender(smtpServer.getSmtp().getPort(), SYNCHRONOUS);
    smtpAppender.setAsynchronousSending(false);
    smtpAppender.setLayout(buildHTMLLayout(lc));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("hello");
    logger.error("an error", new Exception("an exception"));

    MimeMultipart mp = verify(smtpServer, TEST_SUBJECT);

    // verify strict adherence to xhtml1-strict.dtd
    SAXReader reader = new SAXReader();
    reader.setValidation(true);
    reader.setEntityResolver(new XHTMLEntityResolver());
    reader.read(mp.getBodyPart(0).getInputStream());
  }
Пример #24
0
  @Override
  protected void after() {
    if (greenMail != null) {
      // Suppress error from GreenMail on shutdown
      Thread.setDefaultUncaughtExceptionHandler(
          new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
              if (!(e.getCause() instanceof SocketException
                  && t.getClass().getName().equals("com.icegreen.greenmail.smtp.SmtpHandler"))) {
                System.err.print("Exception in thread \"" + t.getName() + "\" ");
                e.printStackTrace(System.err);
              }
            }
          });

      greenMail.stop();
    }
  }
  @Test
  public void multiLineSubjectTruncatedAtFirstNewLine() throws Exception {
    String line1 = "line 1 of subject";
    String subject = line1 + "\nline 2 of subject\n";
    buildSMTPAppender(subject, ASYNCHRONOUS);

    smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("hello");
    logger.error("en error", new Exception("an exception"));

    Thread.yield();
    waitUntilEmailIsSent();
    waitForServerToReceiveEmails(1);

    MimeMessage[] mma = greenMailServer.getReceivedMessages();
    assertEquals(1, mma.length);
    assertEquals(line1, mma[0].getSubject());
  }
 @After
 public void tearDown() throws Exception {
   greenMailServer.stop();
 }
 private void waitForServerToReceiveEmails(int emailCount) throws InterruptedException {
   greenMailServer.waitForIncomingEmail(5000, emailCount);
 }
 @After
 public void stopMailServer() throws Exception {
   greenMail.stop();
 }
Пример #29
0
 @Override
 public void afterPropertiesSet() throws Exception {
   greenMail = new GreenMail(new ServerSetup(port, null, ServerSetup.PROTOCOL_SMTP));
   greenMail.setUser(account, password);
   greenMail.start();
 }
Пример #30
0
 @Override
 public void destroy() throws Exception {
   if (greenMail != null) {
     greenMail.stop();
   }
 }