Java Code Examples for javax.mail.Store

The following examples show how to use javax.mail.Store. These examples are extracted from open source projects. 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 Project: product-es   Source File: EmailUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 2
Source Project: micro-integrator   Source File: GreenMailServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete all emails in the inbox.
 *
 * @param protocol protocol used to connect to the server
 * @throws MessagingException if we're unable to connect to the store
 */
public static void deleteAllEmails(String protocol, GreenMailUser user) throws MessagingException {
    Folder inbox = null;
    Store store = getConnection(user, protocol);
    try {
        inbox = store.getFolder(EMAIL_INBOX);
        inbox.open(Folder.READ_WRITE);
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            message.setFlag(Flags.Flag.DELETED, true);
            log.info("Deleted email Subject : " + message.getSubject());
        }
    } finally {
        if (inbox != null) {
            inbox.close(true);
        }
        if (store != null) {
            store.close();
        }
    }
}
 
Example 3
Source Project: micro-integrator   Source File: GreenMailServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source Project: mnIMAPSync   Source File: StoreCrawler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Source Project: ats-framework   Source File: ImapFolder.java    License: Apache License 2.0 6 votes vote down vote up
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>();
}
 
Example 6
Source Project: ats-framework   Source File: MimePackage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
            }
        }
    }
}
 
Example 7
Source Project: syndesis   Source File: EMailTestServer.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 8
Source Project: syndesis   Source File: EMailTestServer.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 9
Source Project: testgrid   Source File: EmailUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 10
Source Project: product-ei   Source File: GreenMailServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 11
Source Project: product-ei   Source File: GreenMailServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 12
Source Project: product-es   Source File: EmailUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 13
Source Project: product-ei   Source File: GreenMailServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source Project: codenvy   Source File: MailReceiverUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 15
Source Project: smslib-v3   Source File: Email.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Collection<OutboundMessage> getMessagesToSend() throws Exception
{
	List<OutboundMessage> retValue = new ArrayList<OutboundMessage>();
	Store s = this.mailSession.getStore();
	s.connect();
	Folder inbox = s.getFolder(getProperty("mailbox_name", "INBOX"));
	inbox.open(Folder.READ_WRITE);
	for (Message m : inbox.getMessages())
	{
		OutboundMessage om = new OutboundMessage(m.getSubject(), m.getContent().toString());
		om.setFrom(m.getFrom().toString());
		om.setDate(m.getReceivedDate());
		retValue.add(om);
		// Delete message from inbox
		m.setFlag(Flags.Flag.DELETED, true);
	}
	inbox.close(true);
	s.close();
	return retValue;
}
 
Example 16
Source Project: mail-importer   Source File: ThunderbirdMailbox.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 17
Source Project: BotLibre   Source File: Email.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example 18
Source Project: BotLibre   Source File: Email.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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) {}
	}
}
 
Example 19
Source Project: javamail-mock2   Source File: SMTPTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example 20
Source Project: javamail-mock2   Source File: SMTPTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example 21
Source Project: mireka   Source File: MxPopTest.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 22
Source Project: OA   Source File: MessageParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
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
				}
			}
		}
	}

}
 
Example 23
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");
    }
}
 
Example 24
Source Project: micro-integrator   Source File: MailToTransportUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
            }
        }
    }
}
 
Example 25
Source Project: jbang   Source File: imap.java    License: MIT License 5 votes vote down vote up
@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();
}
 
Example 26
Source Project: hop   Source File: MailConnectionTest.java    License: Apache License 2.0 5 votes vote down vote up
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 );

}
 
Example 27
Source Project: NoraUi   Source File: MailSteps.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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));
    }
}
 
Example 28
Source Project: ats-framework   Source File: MimePackage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 29
Source Project: syndesis   Source File: ReceiveEMailVerifierExtension.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 30
Source Project: syndesis   Source File: EMailTestServer.java    License: Apache License 2.0 5 votes vote down vote up
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());
}