Java Code Examples for javax.mail.Session#getStore()

The following examples show how to use javax.mail.Session#getStore() . 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: ThunderbirdMailbox.java    From mail-importer with 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 2
Source File: MailListener.java    From Ardulink-1 with Apache License 2.0 6 votes vote down vote up
private static void initInbox() {
	try {
		System.out.println("Inbox initiating...");

        Properties props = new Properties();
        props.setProperty(MAIL_STORE_PROTOCOL_KEY, mailConfig.getProperty(MAIL_STORE_PROTOCOL_KEY));

        // Used gmail with lesser secure authentication (https://www.google.com/settings/security/lesssecureapps)
        // For a full access I should implement OAuth2 for ArdulinkMail (https://java.net/projects/javamail/pages/OAuth2)
        
        Session session = Session.getInstance(props, null);
		Store store = session.getStore();
		System.out.println(mailConfig.getProperty(MAIL_HOST_KEY) + " " + mailConfig.getProperty(MAIL_USER_KEY) + " " + mailConfig.getProperty(MAIL_PASSWORD_KEY));
        store.connect(mailConfig.getProperty(MAIL_HOST_KEY), mailConfig.getProperty(MAIL_USER_KEY), mailConfig.getProperty(MAIL_PASSWORD_KEY));
        
        // clearDefault(store.getDefaultFolder()); // With GMAIL it doesn't work since "all messages" cannot be cleared.
        clearMainFolder(store.getFolder("INBOX"));
        
        inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);
		System.out.println("Inbox initiated");
	} catch (Exception e) {
		throw new IllegalStateException("Error initiating inbox. Exiting...");
	}
}
 
Example 3
Source File: EmailUtils.java    From testgrid with 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 4
Source File: MxPopTest.java    From mireka with 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:secret@localhost:"
                    + 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 5
Source File: Pop3SecureConnector.java    From bobcat with Apache License 2.0 6 votes vote down vote up
@Override
public void connect() {
  Properties properties = new Properties();
  try {
    int port = configuration.getPort();
    String portS = String.valueOf(port);
    properties.setProperty("mail.store.protocol", "pop3");
    properties.setProperty("mail.pop3.port", portS);
    properties.setProperty("mail.pop3.socketFactory.class",
        "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("mail.pop3.socketFactory.fallback", "true");
    properties.setProperty("mail.pop3.port", portS);
    properties.setProperty("mail.pop3.socketFactory.port", portS);
    URLName url = new URLName("pop3s", configuration.getServer(), port, "",
        configuration.getUsername(), configuration.getPassword());

    Session session = Session.getInstance(properties, null);
    store = session.getStore(url);
    store.connect();
    folder = store.getFolder(configuration.getFolderName());
    folder.open(Folder.READ_WRITE);
  } catch (MessagingException e) {
    LOGGER.error("error - cannot connect to mail server", e);
    throw new ConnectorException(e);
  }
}
 
Example 6
Source File: GreenMailServer.java    From product-ei with 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 7
Source File: EmailUtil.java    From product-es with 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 8
Source File: MaiLoginlAction.java    From scada with MIT License 5 votes vote down vote up
public void connect() throws Exception {
	Properties props = new Properties();// ׼�����ӷ������ĻỰ��Ϣ
	/*-----------------�ɵ����ӷ�ʽ--------------------------------*/
	// props.setProperty("mail.store.protocol", "pop3"); // ��
	// props.setProperty("mail.pop3.port", "110"); // �˿�
	// props.setProperty("mail.pop3.host", this.getHost()); // pop3������
	/*-----------------------------------------------------------*/
	/*------------------�µ����ӷ�ʽ---------------------------------*/
	props.put("mail.smtp.host", "localhost"); // smtp������
	props.put("mail.smtp.auth", "true"); // �Ƿ�smtp��֤
	props.put("mail.smtp.port", "25"); // ����smtp�˿�
	props.put("mail.transport.protocol", "smtp"); // ���ʼ�Э��
	props.put("mail.store.protocol", "pop3"); // ���ʼ�Э��
	props.put("mail.store.host", "localhost");
	/*-----------------------------------------------------------*/
	// ����Sessionʵ������
	Session session = Session.getInstance(props);
	store = session.getStore();
	//sendStore = session.getStore();
	store.connect("scada.com",username, password);
	//sendStore.connect("scada.com", username, password);
	//Folder[] folders = store.getDefaultFolder().list();
	// ����ռ���
	folder = store.getFolder("INBOX");
	// ��÷�����
	//sendFolder = store.getFolder("SENDED");
	/*
	 * Folder.READ_ONLY��ֻ��Ȩ�� Folder.READ_WRITE���ɶ���д�������޸��ʼ���״̬��
	 */
	folder.open(Folder.READ_WRITE); //���ռ���
	//sendFolder.open(POP3Folder.READ_WRITE);// ���ռ���
	// �õ��ռ����е������ʼ�,������
	messages = folder.getMessages();
	//sendMessages = sendFolder.getMessages();
}
 
Example 9
Source File: EmailReader.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected void doInitialize(UimaContext context) throws ResourceInitializationException {
  validateParams();

  Authenticator authenticator =
      new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(user, pass);
        }
      };

  Properties prop = new Properties();
  prop.put("mail.store.protocol", protocol);
  prop.put("mail.host", server);
  prop.put("mail." + protocol + ".port", port);
  prop.put("mail.user", user);

  Session session = Session.getInstance(prop, authenticator);
  try {
    store = session.getStore();
  } catch (NoSuchProviderException e) {
    throw new ResourceInitializationException(e);
  }

  try {
    store.connect();
    inboxFolder = store.getFolder(inbox);
    reopenConnection();
  } catch (MessagingException me) {
    throw new ResourceInitializationException(me);
  }
}
 
Example 10
Source File: MailReceiverUtils.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates session with email server with using IMAP - mail protocol. Return array of the messages
 * from the test mailbox
 *
 * @param user login to test mail box that is used for mail connection
 * @param password password for test mailbox
 * @return array of messages from the mail box exceptions that may be produced during working with
 *     test mailbox:
 * @throws MessagingException
 */
private Message[] receiveMailsFromInbox(String user, String password) throws MessagingException {
  Properties properties = System.getProperties(); // Get system properties
  Session session = Session.getDefaultInstance(properties); // Get the default Session object.
  mailStore =
      session.getStore("imaps"); // Get a Store object that implements the specified protocol.
  mailStore.connect(
      host, user,
      password); // Connect to the current host using the specified username and password.
  mailBoxFolder =
      mailStore.getFolder("inbox"); // Create a Folder object corresponding to the given name.
  mailBoxFolder.open(Folder.READ_ONLY); // Open the Folder.
  Message[] msgs = mailBoxFolder.getMessages();
  return msgs;
}
 
Example 11
Source File: ArdulinkMailOnCamelIntegrationTest.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
private Message retrieveViaImap(String host, int port, String user, String password) throws MessagingException {
	Properties props = new Properties();
	props.setProperty("mail.store.protocol", "imap");
	props.setProperty("mail.imap.port", String.valueOf(port));
	Session session = Session.getInstance(props, null);
	Store store = session.getStore();
	store.connect(host, user, password);
	Folder inbox = store.getFolder("INBOX");
	inbox.open(Folder.READ_ONLY);
	int messageCount = inbox.getMessageCount();
	return messageCount == 0 ? null : inbox.getMessage(1);
}
 
Example 12
Source File: MailUtils.java    From scada with MIT License 5 votes vote down vote up
/**
 * �����ʼ�
 */ 
public static void receive() throws Exception { 
    // ׼�����ӷ������ĻỰ��Ϣ 
    Properties props = new Properties(); 
    props.setProperty("mail.store.protocol", "pop3");       // �� 
    props.setProperty("mail.pop3.port", "110");             // �˿� 
    props.setProperty("mail.pop3.host", "pop3.sina.com");    // pop3������ 
     
    // ����Sessionʵ������ 
    Session session = Session.getInstance(props); 
    Store store = session.getStore("pop3"); 
    store.connect("[email protected]", "mh899821671104"); 
     
    // ����ռ��� 
    Folder folder = store.getFolder("INBOX"); 
    /* Folder.READ_ONLY��ֻ��Ȩ��
     * Folder.READ_WRITE���ɶ���д�������޸��ʼ���״̬��
     */ 
    folder.open(Folder.READ_WRITE); //���ռ��� 
     
    // ����POP3Э���޷���֪�ʼ���״̬,����getUnreadMessageCount�õ������ռ�����ʼ����� 
    System.out.println("δ���ʼ���: " + folder.getUnreadMessageCount()); 
     
    // ����POP3Э���޷���֪�ʼ���״̬,��������õ��Ľ��ʼ�ն���Ϊ0 
    System.out.println("ɾ���ʼ���: " + folder.getDeletedMessageCount()); 
    System.out.println("���ʼ�: " + folder.getNewMessageCount()); 
     
    // ����ռ����е��ʼ����� 
    System.out.println("�ʼ�����: " + folder.getMessageCount()); 
     
    // �õ��ռ����е������ʼ�,������ 
    Message[] messages = folder.getMessages(); 
    parseMessage(messages); 
     
    //�ͷ���Դ 
    folder.close(true); 
    store.close(); 
}
 
Example 13
Source File: StoreMail.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		// 创建一个有具体连接信息的Properties对象
		Properties prop = new Properties();
		prop.setProperty("mail.debug", "true");
		prop.setProperty("mail.store.protocol", "pop3");
		prop.setProperty("mail.pop3.host", MAIL_SERVER_HOST);

		// 1、创建session
		Session session = Session.getInstance(prop);

		// 2、通过session得到Store对象
		Store store = session.getStore();

		// 3、连上邮件服务器
		store.connect(MAIL_SERVER_HOST, USER, PASSWORD);

		// 4、获得邮箱内的邮件夹
		Folder folder = store.getFolder("inbox");
		folder.open(Folder.READ_ONLY);

		// 获得邮件夹Folder内的所有邮件Message对象
		Message[] messages = folder.getMessages();
		for (int i = 0; i < messages.length; i++) {
			String subject = messages[i].getSubject();
			String from = (messages[i].getFrom()[0]).toString();
			System.out.println("第 " + (i + 1) + "封邮件的主题:" + subject);
			System.out.println("第 " + (i + 1) + "封邮件的发件人地址:" + from);
		}

		// 5、关闭
		folder.close(false);
		store.close();
	}
 
Example 14
Source File: ReceiveEMailVerifierExtension.java    From syndesis with 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 15
Source File: MailSteps.java    From NoraUi with 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 16
Source File: EmailUtil.java    From product-es with Apache License 2.0 4 votes vote down vote up
/**
 * This method read e-mails from Gmail inbox and find whether the notification of particular type is found.
 *
 * @param   notificationType    Notification types supported by publisher and store.
 * @return  whether email is found for particular type.
 * @throws  Exception
 */
public static boolean readGmailInboxForNotification(String notificationType) throws Exception {
    boolean isNotificationMailAvailable = false;
    long waitTime = 10000;
    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 inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);

    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isNotificationMailAvailable) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if(!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());

                    if (message.getSubject().contains(notificationType)) {
                        isNotificationMailAvailable = true;

                    }
                    // Optional : deleting the  mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e) {
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }

        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return isNotificationMailAvailable;
}
 
Example 17
Source File: DefaultReceiveEmailProvider.java    From xframium-java with GNU General Public License v3.0 4 votes vote down vote up
public MessageWrapper _getEmail( String hostName, MessageFilter[] messageFilters, Map<String, String> propertyMap )
{
    Properties mailProps = new Properties();
    mailProps.putAll( propertyMap );

    List<Message> messageList = new ArrayList<Message>( 10 );
    MessageWrapper messageWrapper = null;

    try
    {
        Session emailSession = Session.getDefaultInstance( mailProps );
        Store store = emailSession.getStore( propertyMap.get( PROTOCOL ) );
        store.connect( hostName, propertyMap.get( USER_NAME ), propertyMap.get( PASSWORD ) );

        Folder emailFolder = store.getFolder( propertyMap.get( FOLDER_NAME ) != null ? propertyMap.get( FOLDER_NAME ) : DEFAULT_FOLDER_NAME );
        emailFolder.open( Folder.READ_WRITE );

        Message[] messages = emailFolder.getMessages();

        int messageCount = emailFolder.getMessageCount();
        if ( messageCount > MAX_MESSAGES )
            messageCount = MAX_MESSAGES;

        if ( log.isInfoEnabled() )
            log.info( "Processing " + messageCount + " messages" );

        for ( int i = 0; i < messageCount; i++ )
        {
            if ( applyFilters( messages[i], messageFilters ) )
            {
                messageList.add( messages[i] );
            }
        }

        if ( messageList.size() == 0 )
            throw new ScriptException( "Failed to find any email messages that met the criteria" );
            
        Collections.sort( messageList, new DateComparator() );

        String messageContent = null;
        String contentType = messageList.get( 0 ).getContentType();

        if ( contentType.startsWith( "text/" ) )
            messageContent = messageList.get( 0 ).getContent().toString();
        else if ( messageList.get( 0 ).isMimeType( "multipart/*" ) )
            messageContent = getTextFromMimeMultipart( (MimeMultipart) messageList.get( 0 ).getContent() );
        else
            messageContent = messageList.get( 0 ).getContent().getClass().getName();

        messageWrapper = new MessageWrapper( messageList.size(), messageList.get( 0 ).getFrom()[0].toString(), messageList.get( 0 ).getSubject(), messageContent, contentType );

        emailFolder.close( false );
        store.close();
    }
    catch ( Exception e )
    {
        e.printStackTrace();
        throw new ScriptException( "Failed to find email" );
    }

    return messageWrapper;
}
 
Example 18
Source File: EmailUtil.java    From product-es with Apache License 2.0 4 votes vote down vote up
/**
 * This method read e-mails from Gmail inbox and find whether the notification of particular type is found.
 *
 * @param   notificationType    Notification types supported by publisher and store.
 * @return  whether email is found for particular type.
 * @throws  Exception
 */
public static boolean readGmailInboxForNotification(String notificationType) throws Exception {
    boolean isNotificationMailAvailable = false;
    long waitTime = 10000;
    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 inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);

    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isNotificationMailAvailable) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if(!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());

                    if (message.getSubject().contains(notificationType)) {
                        isNotificationMailAvailable = true;

                    }
                    // Optional : deleting the  mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e) {
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }

        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return isNotificationMailAvailable;
}
 
Example 19
Source File: EmailUtil.java    From product-es with Apache License 2.0 4 votes vote down vote up
/**
 * This method read verification e-mail from Gmail inbox and returns the verification URL.
 *
 * @return  verification redirection URL.
 * @throws  Exception
 */
public static String readGmailInboxForVerification() throws Exception {
    boolean isEmailVerified = false;
    long waitTime = 10000;
    String pointBrowserURL = "";
    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 inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);
    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isEmailVerified) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());
                    if (message.getSubject().contains("EmailVerification")) {
                        pointBrowserURL = getBodyFromMessage(message);
                        isEmailVerified = true;
                    }

                    // Optional : deleting the mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e){
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }
        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count*waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return pointBrowserURL;
}
 
Example 20
Source File: POP3Client.java    From OA with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) {
        Properties props = System.getProperties();
        String host = "pop3.163.com";
        String username = "[email protected]";
        String password = "song5438";
        String provider = "pop3";
        try {
            // 连接到POP3服务器
            Session ss = Session.getDefaultInstance(props, null);
            ss.setDebug(false);
            // 向回话"请求"一个某种提供者的存储库,是一个POP3提供者
            Store store = ss.getStore(provider);
            // 连接存储库,从而可以打开存储库中的文件夹,此时是面向IMAP的
            store.connect(host, username, password);
            // 打开文件夹,此时是关闭的,只能对其进行删除或重命名,无法获取关闭文件夹的信息
            // 从存储库的默认文件夹INBOX中读取邮件
            Folder inbox = store.getFolder("INBOX");
            if (inbox == null) {
                System.out.println("NO INBOX");
                System.exit(1);
            }
            // 打开文件夹,读取信息
            inbox.open(Folder.READ_ONLY);
            System.out.println("TOTAL EMAIL:" + inbox.getMessageCount());
            // 获取邮件服务器中的邮件
            Message[] messages = inbox.getMessages();
            for (int i = 0; i < messages.length; i++) {
                System.out.println("------------Message--" + (i + 1)
                        + "------------");
                // 解析地址为字符串
                String from = InternetAddress.toString(messages[i].getFrom());
                if (from != null) {
                    String cin = getChineseFrom(from);
                    System.out.println("From:" + cin);
                }
                String replyTo = InternetAddress.toString(messages[i]
                        .getReplyTo());
                if (replyTo != null){
                    String rest = getChineseFrom(replyTo);
                    System.out.println("Reply To" + rest);
                }
                String to = InternetAddress.toString(messages[i]
                        .getRecipients(Message.RecipientType.TO));
                if (to != null) {
                    String tos = getChineseFrom(to);
                    System.out.println("To:" + tos);
                }
                String subject = messages[i].getSubject();
                if (subject != null)
                    System.out.println("Subject:" + subject);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date sent = messages[i].getSentDate();
                if (sent != null)
                    System.out.println("Sent Date:" + sdf.format(sent));
                Date ress = messages[i].getReceivedDate();
                if (ress != null)
                    System.out.println("Receive Date:" + sdf.format(ress));
         
//                Multipart multipart = (Multipart)messages[i].getContent();
//                for (int j=0, n=multipart.getCount(); j<n; j++) {
//                Part part = multipart.getBodyPart(j); 
//                String disposition = part.getDisposition(); 
//                if ((disposition != null) && (disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE))) {   
////                	saveFile(part.getFileName(), part.getInputStream());
//                 }
//                }
            }
            // 关闭连接,但不删除服务器上的消息
            // false代表不是删除
            inbox.close(false);
            store.close();
        } catch (Exception e) {
            System.err.println(e);
        }
    }