package com.tutego.insel.mail;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.ContentType;
import javax.swing.JOptionPane;

public class GetEMails
{
  public static void getMail( final Properties props ) throws Exception
  {
    Session session = Session.getInstance( props, new javax.mail.Authenticator() {
          @Override protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication( props.getProperty( "mail.pop3.user" ),
                                               props.getProperty( "mail.pop3.password" ) );
          }
        } );
    session.setDebug( true );

    Store store = session.getStore( "pop3" );
    store.connect();

    Folder folder = store.getFolder( "INBOX" );
    folder.open( Folder.READ_ONLY );

    Message message[] = folder.getMessages();

    for ( int i = 0; i < message.length; i++ )
    {
      Message m = message[i];

      System.out.println( "-------------------------\nNachricht: " + i );
      System.out.println( "Von: " + Arrays.toString(m.getFrom()) );
      System.out.println( "Betreff: " + m.getSubject() );
      System.out.println( "Gesendet am: " + m.getSentDate() );
      System.out.println( "Content-Type: " + new ContentType(m.getContentType()) );

      if ( m.isMimeType("text/plain") )
        System.out.println( m.getContent() );
    }
    folder.close( false );
    store.close();
  }

  public static void main( String[] args ) throws Exception
  {
    Properties props = new Properties();
    props.setProperty( "mail.pop3.host", "pop.gmail.com" );
    props.setProperty( "mail.pop3.user", JOptionPane.showInputDialog( "user" ) );
    props.setProperty( "mail.pop3.password", JOptionPane.showInputDialog( "pass" ) );
    props.setProperty( "mail.pop3.port", "995" );
    props.setProperty( "mail.pop3.auth", "true" );
    props.setProperty( "mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory" );

    getMail( props );
  }
}
