Switch to full style
General Java code examples
Post a reply

Read your gmail using Java code

Sat Nov 27, 2010 9:34 pm

The following code allow you to download the email content using for example POP protocol.You can change the protocol you are using by changing the properties values your are using. If you want to run this code in you project , you may need to remove small things for example (GUILogger lines ). This code allow you to read the email even if you have multi-parts (like attachments ,images , and text ) and change emails read status .

Note : You must have the Java mail library in your build path .
Code:
package mailtest.control;

import com.sun.mail.pop3.POP3SSLStore;
import java.io.IOException;
import java.security.Security;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.swing.JOptionPane;
import mailtest.config.ConfigurationData;
import mailtest.customgui.GUILogger;

/**
*
* @author Mohamed.Sami
*/
public class MailControl {

    private ConfigurationData configurationData = new ConfigurationData();
    private GUILogger gUILogger = GUILogger.getInstance();
    private Session session;
    private Store store;
    private Folder folder;
    private Message[] messages;
    private FetchProfile fetchProfile;
    private Properties properties;
    private String username;
    private String password;

    public MailControl() {
        init();
    }

    public final void init() {

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        properties = configurationData.getProperties();

        if (properties != null) {

            session = Session.getInstance(properties, null);
            int port = Integer.parseInt(properties.getProperty("port"));
            URLName urln = new URLName(properties.getProperty("protocal"), properties.getProperty("host"), port, null, username, password);
            gUILogger.logInfo("Started connecting to mail inbox ... ");
            store = new POP3SSLStore(session, urln);


        } else {
            JOptionPane.showMessageDialog(null,
                    " No properties loaded- Mail Connector Failed .",
                    "Mail client Error", JOptionPane.ERROR_MESSAGE);
            gUILogger.logInfo("No properties loaded- Mail Connector Failed");
        }



    }

    public Message[] readAllMessages() {

        if (properties == null) {
            gUILogger.logInfo("No properties loaded- Mail Connector Failed");
            return null;
        }
        try {
            store.connect(properties.getProperty("host"), username, password);
        } catch (MessagingException ex) {
            JOptionPane.showMessageDialog(null,
                    " couldn't connect to mail server ,please make sure you entered to right(username,password). Or make sure of your mail client connect configuration under props/config.properties file.",
                    "Mail client Error", JOptionPane.ERROR_MESSAGE);
            gUILogger.logInfo("Mail Connector Failed -" + ex);

        }
        try {

            folder = store.getDefaultFolder();
            folder = folder.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            gUILogger.logInfo("Message Count Found " + folder.getMessageCount());
            gUILogger.logInfo("New Message Count " + folder.getNewMessageCount());
            gUILogger.logInfo("=========================================");
            Message[] newmessages = folder.getMessages();
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            folder.fetch(newmessages, fp);
            messages = newmessages;
            return messages;
        } catch (MessagingException ex) {
            JOptionPane.showMessageDialog(null,
                    "Reading the messages INBOX failed -" + ex,
                    "Mail client Error", JOptionPane.ERROR_MESSAGE);
            gUILogger.logInfo("Reading the messages INBOX failed -" + ex);
        }



        return messages;

    }

    public void refresh() {
        readAllMessages();
    }

    public ConfigurationData getConfigurationData() {
        return configurationData;
    }

    public void setConfigurationData(ConfigurationData configurationData) {
        this.configurationData = configurationData;
    }

    public FetchProfile getFetchProfile() {
        return fetchProfile;
    }

    public void setFetchProfile(FetchProfile fetchProfile) {
        this.fetchProfile = fetchProfile;
    }

    public Folder getFolder() {
        return folder;
    }

    public void setFolder(Folder folder) {
        this.folder = folder;
    }

    public GUILogger getgUILogger() {
        return gUILogger;
    }

    public void setgUILogger(GUILogger gUILogger) {
        this.gUILogger = gUILogger;
    }

    public Message[] getMessages() {
        return messages;
    }

    public void setMessages(Message[] messages) {
        this.messages = messages;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public Store getStore() {
        return store;
    }

    public void setStore(Store store) {
        this.store = store;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public void finalize() {
        try {
            try {
                folder.close(true);
                store.close();
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
            super.finalize();
        } catch (Throwable ex) {
            Logger.getLogger(MailControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public ArrayList<String> transform(Message[] messages) {

        if (messages == null || messages.length == 0) {
            gUILogger.logInfo("No messages found to transform");
            return null;
        }

        ArrayList<String> arrayList = new ArrayList<String>();
        String string = null;
        for (int i = 0; i < messages.length;
                i++) {

            try {


                Address[] addressList = messages[i].getFrom();
                for (int j = 0; j < addressList.length; j++) {
                    System.out.println("From address #" + j + " : " + addressList[j].toString());
                }
                System.out.println("Receive date :" + messages[i].getSentDate());
                if (messages[i].isMimeType("text/plain")) {

                    string = messages[i].getContent().toString();


                } else {
                    string = handleMultipart(messages[i]);


                }
                if (string != null) {
                    arrayList.add(string);
                    string = null;
                }

            } catch (MessagingException ex) {
                JOptionPane.showMessageDialog(null,
                        "Messages transformation failed :" + ex,
                        "Mail client Error", JOptionPane.ERROR_MESSAGE);
                gUILogger.logInfo("Messages transformation failed :" + ex);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null,
                        "Messages I/O transformation failed :" + ex,
                        "Mail client Error", JOptionPane.ERROR_MESSAGE);
                gUILogger.logInfo("Messages I/O transformation failed : " + ex);
            }


        }
        return arrayList;
    }

    public String handleMultipart(Message msg) {

        String content = null;
        try {
            String disposition;
            BodyPart part;
            Multipart mp = (Multipart) msg.getContent();

            int mpCount = mp.getCount();
            for (int m = 0; m < mpCount; m++) {
                part = mp.getBodyPart(m);
             
                disposition = part.getDisposition();
                if (disposition != null && disposition.equals(Part.INLINE)) {
                    content = part.getContent().toString();
                } else {
                    content = part.getContent().toString();

                }
            }
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null,
                    "Messages - Parts - Input/output transformation failed :" + ex,
                    "Mail client Error", JOptionPane.ERROR_MESSAGE);
            gUILogger.logInfo("Messages - Parts - Input/output transformation failed :" + ex);
        } catch (MessagingException ex) {
            JOptionPane.showMessageDialog(null,
                    "Messages - Parts - transformation failed :" + ex,
                    "Mail client Error", JOptionPane.ERROR_MESSAGE);
            gUILogger.logInfo("Messages - Parts - transformation failed :" + ex);
        }
        return content;
    }
}


The properties file used in my case :
Code:

mail
.pop3.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail
.pop3.socketFactory.fallback=false
mail
.pop3.port=995
mail
.pop3.socketFactory.port=995
mail
.pop3.host=pop.gmail.com
mail
.pop3.ssl=true
port
=995
protocal
=pop3
host
=pop.gmail.com





Re: Read your gmail using Java code

Tue Oct 18, 2011 7:45 am

Thanks for this code. How can i read only the unread mails?

Re: Read your gmail using Java code

Wed Oct 26, 2011 12:50 pm

To read unread mails only, use flags
Code:

   
try {

            
folder store.getFolder("INBOX");

            
folder.open(Folder.READ_WRITE);
            
gUILogger.logGood("Message Count Found " folder.getMessageCount());
            
gUILogger.logToFile("Message Count Found " folder.getMessageCount());
            
gUILogger.logGood("New Message Count " folder.getNewMessageCount());
            
gUILogger.logToFile("New Message Count " folder.getNewMessageCount());
            
gUILogger.logGood("Unread Message Count " folder.getUnreadMessageCount());
            
gUILogger.logToFile("Unread Message Count " folder.getUnreadMessageCount());
            
gUILogger.logInfo("=========================================");
            
Message[] newmessages folder.getMessages();


            
FetchProfile fp = new FetchProfile();
            
fp.add(FetchProfile.Item.ENVELOPE);
            
fp.add(FetchProfile.Item.FLAGS);
            
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            
newmessages folder.getMessages();

            
//folder.fetch(newmessages, fp);
            
newmessages folder.search(ft);
            
messages newmessages;

            return 
messages;
        } catch (
MessagingException ex) {

            
gUILogger.logError("Reading the messages INBOX failed -" ex);
        }

 


Re: Read your gmail using Java code

Tue Jan 31, 2012 12:36 pm

what is this ConfigurationData

Re: Read your gmail using Java code

Wed Feb 01, 2012 2:23 am

Code:


import java
.io.File;
import java.util.Properties;
import mailtest.customgui.GUILogger;

/**
 *

 */
public class ConfigurationData {

    private Properties properties = null;
    private String filePath = "./props/config.properties";

    public ConfigurationData() {
        loadProperties();
    }

    public ConfigurationData(String filePath) {
        loadProperties(filePath);

    }

    public final void loadProperties(String filePath) {
        this.filePath = filePath;
        loadProperties();
    }

    public final void loadProperties() {
        GUILogger.getInstance().logInfo("Loading configuration from " + filePath);
        try {


            properties = PropertiesUtility.load(new File(filePath));
        } catch (Exception ex) {
            ex.printStackTrace();
            GUILogger.getInstance().logInfo("Error while loading configuration " + ex);
        }
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }
}
 


Re: Read your gmail using Java code

Wed Feb 01, 2012 11:45 am

Thank you....

But......


i am created a new class

public class Main {
public Main() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

try {
ReadInbox gmail=new ReadInbox();

gmail.setUsername("XXXXXX");
gmail.setPassword("XXXXXXX");
gmail.refresh();
gmail.readAllMessages();

//gmail.init();



} catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}

}
}



now i got error


your ID is : xxxxxx
Connecting...
Connected...
java.lang.IllegalStateException: already connected
at javax.mail.Service.connect(Service.java:198)
at javax.mail.Service.connect(Service.java:156)
at com.ReadInbox.readAllMessages(ReadInbox.java:91)
at com.ReadInbox.refresh(ReadInbox.java:127)
at com.Main.main(Main.java:17)

Re: Read your gmail using Java code

Fri Mar 16, 2012 3:23 am

please add the gui code also i need to check the my mail through java in first time. i run my program but i got error in the program. please help me anybody and send me a solution. following my codes and error.

import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;

public class SimpleMail {

public synchronized void sendMail(String subject, String body, String sender, String recipients)
throws Exception {

String mailhost = "smtp.gmail.com";
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {

@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username of authentication mail account", "password of authentication mail account");

}
});

MimeMessage message = new MimeMessage(session);
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setContent(body, "text/plain");
if (recipients.indexOf(',') > 0) {
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
} else {
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
}


Transport.send(message);

}

public static void main(String args[]) throws Exception {
SimpleMail mailutils = new SimpleMail();
mailutils.sendMail("test", "helo test from kites", "[email protected]", "[email protected]");

}
}


my error is


Exception in thread "main" javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1211)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:311)
at javax.mail.Service.connect(Service.java:255)
at javax.mail.Service.connect(Service.java:134)
at javax.mail.Service.connect(Service.java:86)
at com.sun.mail.smtp.SMTPTransport.connect(SMTPTransport.java:144)
at javax.mail.Transport.send0(Transport.java:150)
at javax.mail.Transport.send(Transport.java:80)
at com.kitesnet.database.SimpleMail.sendMail(SimpleMail.java:54)
at com.kitesnet.database.SimpleMail.main(SimpleMail.java:60)
Java Result: 1



i hope any one will help me. :beg:

Re: Read your gmail using Java code

Fri Mar 16, 2012 10:17 am

Actually i think the problem in the host name , i have used POP3 protocal ,as i remember SMTP is used for sending emails
use these :
Code:

mail
.pop3.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail
.pop3.socketFactory.fallback=false
mail
.pop3.port=995
mail
.pop3.socketFactory.port=995
mail
.pop3.host=pop.gmail.com
mail
.pop3.ssl=true
port
=995
protocal
=pop3
host
=pop.gmail.com



Re: Read your gmail using Java code

Fri Mar 23, 2012 7:43 am

Can you post the whole code or link to your project.

Re: Read your gmail using Java code

Thu Apr 05, 2012 6:01 am

pls post the gui logger class code

Post a reply
  Related Posts  to : Read your gmail using Java code
 simple code to read properties in java     -  
 Read list of files in java I/O code     -  
 Read stream from URL using Java     -  
 Write and Read to File In Java Example     -  
 Read double values type from file in java     -  
 Algorithms code in java     -  
 GamePLay java code ( please help )     -  
 java code for chat     -  
 need java client/server code     -  
 Adler-32 checksum java code     -  

Topic Tags

Java Email