类javax.mail.Store源码实例Demo

下面列出了怎么用javax.mail.Store的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: product-es   文件: EmailUtil.java
/**
 * This method delete all the sent mails. Can be used after a particular test class
 *
 * @throws  MessagingException
 * @throws  IOException
 */
public static void deleteSentMails() throws MessagingException, IOException {
    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 sentMail = store.getFolder("[Gmail]/Sent Mail");
    sentMail.open(Folder.READ_WRITE);
    Message[] messages =sentMail.getMessages();
    Flags deleted = new Flags(Flags.Flag.DELETED);
    sentMail.setFlags(messages,deleted,true);
    sentMail.close(true);
    store.close();
}
 
源代码2 项目: micro-integrator   文件: GreenMailServer.java
/**
 * 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();
        }
    }
}
 
源代码3 项目: micro-integrator   文件: GreenMailServer.java
/**
 * 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;
}
 
源代码4 项目: mnIMAPSync   文件: StoreCrawler.java
/**
 * Static method to populate a {@link Index} with the messages in an {@link Store}
 */
public static Index populateFromStore(final Index index, Store store, int threads)
    throws MessagingException, InterruptedException {

  MessagingException messagingException = null;
  final ExecutorService service = Executors.newFixedThreadPool(threads);
  try {
    index.setFolderSeparator(String.valueOf(store.getDefaultFolder().getSeparator()));
    crawlFolders(store, index, store.getDefaultFolder(), service);
  } catch (MessagingException ex) {
    messagingException = ex;
  }
  service.shutdown();
  service.awaitTermination(1, TimeUnit.HOURS);
  if (index.hasCrawlException()) {
    messagingException = index.getCrawlExceptions().iterator().next();
  }
  if (messagingException != null) {
    throw messagingException;
  }
  return index;
}
 
源代码5 项目: ats-framework   文件: ImapFolder.java
ImapFolder( Store store,
            String serverHost,
            String folderName,
            String userName,
            String password ) {

    this.isOpen = false;
    this.store = store;
    this.serverHost = serverHost;
    this.folderName = folderName;
    this.userName = userName;
    this.password = password;

    newMetaDataList = new ArrayList<MetaData>();
    allMetaDataList = new ArrayList<MetaData>();
}
 
源代码6 项目: ats-framework   文件: MimePackage.java
/**
 * Close connection
 * <b>Note</b>Internal method
 * @throws MessagingException
 */
public void closeStoreConnection(
                                  boolean storeConnected ) throws MessagingException {

    if (storeConnected) {
        // the folder is empty when the message is not loaded from IMAP server, but from a file
        Folder imapFolder = message.getFolder();
        if (imapFolder == null) {
            imapFolder = partOfImapFolder; // in case of nested package but still originating from IMAP server
        }
        if (imapFolder != null) {
            Store store = imapFolder.getStore();
            if (store != null && store.isConnected()) {
                // closing store closes and its folders
                log.debug("Closing store (" + store.toString() + ") and associated folders");
                store.close();
            }
        }
    }
}
 
源代码7 项目: syndesis   文件: EMailTestServer.java
public int getEmailCountInFolder(String user, String password, String folderName) throws Exception {
    if (server instanceof SmtpServer) {
        throw new Exception("SMTP not applicable for reading folders");
    }

    Store store = server.createStore();
    store.connect(user, password);

    Folder newFolder = store.getFolder(folderName);
    if (! newFolder.exists()) {
        throw new Exception("No folder with name " + folderName);
    }

    newFolder.open(Folder.READ_ONLY);
    return newFolder.getMessageCount();
}
 
源代码8 项目: syndesis   文件: EMailTestServer.java
public List<EMailMessageModel> getEmailsInFolder(String user, String password, String folderName) throws Exception {
    if (server instanceof SmtpServer) {
        throw new Exception("SMTP not applicable for reading folders");
    }

    Store store = server.createStore();
    store.connect(user, password);

    Folder newFolder = store.getFolder(folderName);
    if (! newFolder.exists()) {
        throw new Exception("No folder with name " + folderName);
    }

    newFolder.open(Folder.READ_ONLY);
    List<EMailMessageModel> models = new ArrayList<>();
    for (Message msg : newFolder.getMessages()) {
        models.add(createMessageModel(msg));
    }

    return models;
}
 
源代码9 项目: testgrid   文件: EmailUtils.java
/**
 * Connects to email server with credentials provided to read from a given folder of the email application
 *
 * @param username    Email username (e.g. [email protected])
 * @param password    Email password
 * @param server      Email server (e.g. smtp.email.com)
 * @param emailFolder Folder in email application to interact with
 */
public EmailUtils(String username, String password, String server, EmailFolder emailFolder)
        throws MessagingException {

    Properties props = System.getProperties();

    try {
        props.load(new FileInputStream(new File("../src/test/resources/email.properties")));
    } catch (Exception e) {
        logger.error("Error occured while reading email properties ", e);
        System.exit(-1);
    }

    Session session = Session.getInstance(props);
    Store store = session.getStore("imaps");
    store.connect(server, username, password);

    folder = store.getFolder(emailFolder.getText());
    folder.open(Folder.READ_WRITE);
}
 
源代码10 项目: product-ei   文件: GreenMailServer.java
/**
 * 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;
}
 
源代码11 项目: product-ei   文件: GreenMailServer.java
/**
 * 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;
}
 
源代码12 项目: product-es   文件: EmailUtil.java
/**
 * This method delete all the sent mails. Can be used after a particular test class
 *
 * @throws  MessagingException
 * @throws  IOException
 */
public static void deleteSentMails() throws MessagingException, IOException {
    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 sentMail = store.getFolder("[Gmail]/Sent Mail");
    sentMail.open(Folder.READ_WRITE);
    Message[] messages =sentMail.getMessages();
    Flags deleted = new Flags(Flags.Flag.DELETED);
    sentMail.setFlags(messages,deleted,true);
    sentMail.close(true);
    store.close();
}
 
源代码13 项目: product-ei   文件: GreenMailServer.java
/**
 * 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;
}
 
源代码14 项目: codenvy   文件: MailReceiverUtils.java
/**
 * 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);
}
 
源代码15 项目: smslib-v3   文件: Email.java
@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;
}
 
源代码16 项目: mail-importer   文件: ThunderbirdMailbox.java
public JavaxMailStorage get() throws MessagingException {
  Properties properties = new Properties();
  properties.setProperty("mail.store.protocol", "mstor");
  properties.setProperty("mstor.mbox.metadataStrategy", "none");
  properties.setProperty("mstor.mbox.cacheBuffers", "disabled");
  properties.setProperty("mstor.mbox.bufferStrategy", "mapped");
  properties.setProperty("mstor.metadata", "disabled");
  properties.setProperty("mstor.mozillaCompatibility", "enabled");

  Session session = Session.getDefaultInstance(properties);

  // /Users/flan/Desktop/Copy of Marie's Mail/Mail/Mail/mail.lean.to
  File mailbox = new File(commandLineArguments.mailboxFileName);
  if (!mailbox.exists()) {
    throw new MessagingException("No such mailbox:" + mailbox);
  }

  Store store = session.getStore(
      new URLName("mstor:" + mailbox.getAbsolutePath()));
  store.connect();

  return new ThunderbirdMailStorage(
      logger,
      new JavaxMailFolder(store.getDefaultFolder()),
      statusParser);
}
 
源代码17 项目: BotLibre   文件: Email.java
public Store connectStore() throws MessagingException {
	initProperties();
	if (isSSLRequired()) {
		return connectStoreSSL();
	}
	Properties properties = new Properties();
	properties.put("mail." + getProtocol() + ".timeout", TIMEOUT);
	properties.put("mail." + getProtocol() + ".connectiontimeout", TIMEOUT);
	//properties.setProperty("mail.store.protocol", getProtocol());
	Session session = Session.getInstance(properties, null);
	Store store = session.getStore(getProtocol());
	if (getIncomingPort() == 0) {
		store.connect(getIncomingHost(), getUsername(), getPassword());
	} else {
		store.connect(getIncomingHost(), getIncomingPort(), getUsername(), getPassword());
	}
	return store;
}
 
源代码18 项目: BotLibre   文件: Email.java
/**
 * Connect and verify the email settings.
 */
public void connect() {
	Store store = null;
	try {
		log("Connecting email.", Level.FINER);
		store = connectStore();
		connectSession();
		log("Done connecting email.", Level.FINER);
	} catch (MessagingException messagingException) {
		BotException exception = new BotException("Failed to connect - " + messagingException.getMessage(), messagingException);
		log(exception);
		throw exception;
	} finally {
		try {
			if (store != null) {
				store.close();
			}
		} catch (Exception ignore) {}
	}
}
 
源代码19 项目: javamail-mock2   文件: SMTPTestCase.java
@Test
public void test2SendMessage2() throws Exception {

    final Transport transport = session.getTransport(Providers.getSMTPProvider("makes_no_difference_here", true, true));

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test 1");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    transport.sendMessage(msg, new Address[] { new InternetAddress("[email protected]") });

    final Store store = session.getStore("mock_pop3");
    store.connect("[email protected]", null);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(1, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));
    Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
    inbox.close(false);

}
 
源代码20 项目: javamail-mock2   文件: SMTPTestCase.java
@Test
public void test3SendMessage() throws Exception {

    Session.getDefaultInstance(getProperties());

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test 1");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    Transport.send(msg);

    final Store store = session.getStore("mock_pop3");
    store.connect("[email protected]", null);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Assert.assertEquals(1, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));
    Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
    inbox.close(false);

}
 
源代码21 项目: mireka   文件: MxPopTest.java
private void retrieveMail() throws NoSuchProviderException,
        MessagingException, IOException {
    Properties properties = new Properties();
    Session session = Session.getInstance(properties);
    Store store =
            session.getStore(new URLName("pop3://john:[email protected]:"
                    + PORT_POP + "/INBOX"));
    store.connect();
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    Message[] messages = folder.getMessages();
    assertEquals(1, messages.length);
    Message message = messages[0];
    assertEquals("Hello World!\r\n", message.getContent());
    message.setFlag(Flags.Flag.DELETED, true);
    folder.close(true);
    store.close();
}
 
源代码22 项目: OA   文件: MessageParser.java
public static void parse(Message... messages) {
	if (messages == null || messages.length == 0) {
		System.out.println("没有任何邮件");
	} else {
		for (Message m : messages) {
			parse(m);
		}
		// 最后关闭连接
		if (messages[0] != null) {
			Folder folder = messages[0].getFolder();
			if (folder != null) {
				try {
					Store store = folder.getStore();
					folder.close(false);// 参数false表示对邮件的修改不传送到服务器上
					if (store != null) {
						store.close();
					}
				} catch (MessagingException e) {
					// ignore
				}
			}
		}
	}

}
 
protected void checkStoreForTestConnection(final Store store) {
    if (!store.isConnected()) {
        IMAPUtils.close(store);
        throw new RuntimeException("Store not connected");
    }

    if (!store.getURLName().getUsername().toLowerCase().startsWith("es_imapriver_unittest")) {
        IMAPUtils.close(store);
        throw new RuntimeException("User " + store.getURLName().getUsername() + " belongs not to a valid test mail connection");
    }
}
 
源代码24 项目: micro-integrator   文件: MailToTransportUtil.java
/**
 * Check a particular email has received to a given email folder by email subject.
 *
 * @param emailSubject - Email emailSubject to find email is in inbox or not
 * @return - found the email or not
 * @throws ESBMailTransportIntegrationTestException - Is thrown if an error occurred while reading the emails
 */
public static boolean isMailReceivedBySubject(String emailSubject, String folder)
        throws ESBMailTransportIntegrationTestException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection();
    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 emailSubject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
        return emailReceived;
    } catch (MessagingException ex) {
        log.error("Error when getting mail count ", ex);
        throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex);
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                log.warn("Error when closing the store ", e);
            }
        }
    }
}
 
源代码25 项目: jbang   文件: imap.java
@Override
public Integer call() throws Exception {
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect(host, username, password);
    //System.out.println(store);

    Folder f = store.getFolder(folder);
    System.out.println(f.getName() + ":" + f.getUnreadMessageCount());

    return f.getUnreadMessageCount();
}
 
源代码26 项目: hop   文件: MailConnectionTest.java
public Mconn( ILogChannel log ) throws HopException, MessagingException {
  super( log, MailConnectionMeta.PROTOCOL_IMAP, "junit", 0, "junit", "junit", false, false, "junit" );

  store = Mockito.mock( Store.class );

  inbox = Mockito.mock( Folder.class );
  a = Mockito.mock( Folder.class );
  b = Mockito.mock( Folder.class );
  c = Mockito.mock( Folder.class );

  when( a.getFullName() ).thenReturn( "A" );
  when( b.getFullName() ).thenReturn( "B" );
  when( c.getFullName() ).thenReturn( "C" );

  when( a.exists() ).thenReturn( true );
  when( b.exists() ).thenReturn( true );
  when( c.exists() ).thenReturn( cCreated );
  when( c.create( Mockito.anyInt() ) ).thenAnswer( new Answer<Boolean>() {
    @Override
    public Boolean answer( InvocationOnMock invocation ) throws Throwable {
      Object arg0 = invocation.getArguments()[ 0 ];
      mode = Integer.class.cast( arg0 );
      cCreated = true;
      return true;
    }
  } );

  when( inbox.getFolder( "a" ) ).thenReturn( a );
  when( a.getFolder( "b" ) ).thenReturn( b );
  when( b.getFolder( "c" ) ).thenReturn( c );

  when( store.getDefaultFolder() ).thenReturn( inbox );

}
 
源代码27 项目: NoraUi   文件: MailSteps.java
/**
 * Valid activation email.
 *
 * @param mailHost
 *            example: imap.gmail.com
 * @param mailUser
 *            login of mail box
 * @param mailPassword
 *            password of mail box
 * @param senderMail
 *            sender of mail box
 * @param subjectMail
 *            subject of mail box
 * @param firstCssQuery
 *            the first matching element
 * @param conditions
 *            list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
 * @throws TechnicalException
 *             is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
 *             Exception with message and with screenshot and with exception if functional error but no screenshot and no exception if technical error.
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
@Experimental(name = "validActivationEmail")
@RetryOnFailure(attempts = 3, delay = 60)
@Conditioned
@Et("Je valide le mail d'activation {string}(\\?)")
@And("I valid activation email {string}(\\?)")
public void validActivationEmail(String mailHost, String mailUser, String mailPassword, String senderMail, String subjectMail, String firstCssQuery, List<GherkinStepCondition> conditions)
        throws FailureException, TechnicalException {
    try {
        final Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imap");
        final Session session = Session.getDefaultInstance(props, null);
        final Store store = session.getStore("imaps");
        store.connect(mailHost, mailUser, mailPassword);
        final Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        final SearchTerm filterA = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        final SearchTerm filterB = new FromTerm(new InternetAddress(senderMail));
        final SearchTerm filterC = new SubjectTerm(subjectMail);
        final SearchTerm[] filters = { filterA, filterB, filterC };
        final SearchTerm searchTerm = new AndTerm(filters);
        final Message[] messages = inbox.search(searchTerm);
        for (final Message message : messages) {
            validateActivationLink(subjectMail, firstCssQuery, message);
        }
    } catch (final Exception e) {
        new Result.Failure<>("", Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_MAIL_ACTIVATION), subjectMail), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
    }
}
 
源代码28 项目: ats-framework   文件: MimePackage.java
/**
 * Reconnects if connection is closed.
 * <b>Note</b>Internal method
 * @return true if store re-connection is performed and this means that close should be closed after the work is done
 * @throws MessagingException
 */
public boolean reconnectStoreIfClosed() throws MessagingException {

    boolean storeReconnected = false;

    // the folder is empty when the message is not loaded from IMAP server, but from a file
    Folder imapFolder = message.getFolder();
    if (imapFolder == null) {
        imapFolder = this.partOfImapFolder;
    } else {
        partOfImapFolder = imapFolder; // keep reference
    }
    if (imapFolder != null) {
        Store store = imapFolder.getStore();
        if (store != null) {
            if (!store.isConnected()) {
                log.debug("Reconnecting store... ");
                store.connect();
                storeReconnected = true;
            }

            // Open folder in read-only mode
            if (!imapFolder.isOpen()) {
                log.debug("Reopening folder " + imapFolder.getFullName()
                          + " in order to get contents of mail message");
                imapFolder.open(Folder.READ_ONLY);
            }
        }
    }
    return storeReconnected;
}
 
源代码29 项目: syndesis   文件: ReceiveEMailVerifierExtension.java
@Override
protected Result verifyConnectivity(Map<String, Object> parameters) {
    ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);

    try {
        MailConfiguration configuration = createConfiguration(parameters);

        String timeoutVal = ConnectorOptions.extractOption(parameters, CONNECTION_TIMEOUT);
        if (ObjectHelper.isEmpty(timeoutVal)) {
            timeoutVal = Long.toString(DEFAULT_CONNECTION_TIMEOUT);
        }

        setConnectionTimeoutProperty(parameters, configuration, timeoutVal);

        JavaMailSender sender = createJavaMailSender(configuration);
        Session session = sender.getSession();

        Store store = session.getStore(configuration.getProtocol());
        try {
            store.connect(configuration.getHost(), configuration.getPort(),
                          configuration.getUsername(), configuration.getPassword());
        } finally {
            if (store.isConnected()) {
                store.close();
            }
        }
    } catch (Exception e) {
        ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage())
            .detail("mail_exception_message", e.getMessage()).detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName())
            .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e);

        builder.error(errorBuilder.build());
    }

    return builder.build();
}
 
源代码30 项目: syndesis   文件: EMailTestServer.java
public void generateFolder(String user, String password, String folderName) throws Exception {
    if (server instanceof SmtpServer) {
        throw new Exception("SMTP not applicable for generating folders");
    }

    Store store = server.createStore();
    store.connect(user, password);

    Folder newFolder = store.getFolder(folderName);
    if (! newFolder.exists()) {
        newFolder.create(Folder.HOLDS_MESSAGES);
        assertTrue(newFolder.exists());
    }

    newFolder.open(Folder.READ_WRITE);
    assertTrue(newFolder.isOpen());

    List<MimeMessage> msgs = new ArrayList<>();
    for (int i = 1; i <= 5; ++i) {
        // Use random content to avoid potential residual lingering problems
        String subject = folderName + SPACE + HYPHEN + SPACE + GreenMailUtil.random();
        String body = folderName + NEW_LINE + GreenMailUtil.random();
        GreenMailUser greenUser = greenMail.setUser(user, password);
        msgs.add(createTextMessage(greenUser.getEmail(), "Ben" + i + "@test.com", subject, body)); // Construct message
    }

    newFolder.appendMessages(msgs.toArray(new MimeMessage[0]));
    assertEquals(msgs.size(), newFolder.getMessageCount());
}
 
 类所在包
 同包方法