Total members 10261 | Gratitudes |It is currently Tue May 22, 2012 5:10 pm Login / Join Codemiles


All times are UTC [ DST ]




Post new topic Reply to topic  Quick reply  [ 13 posts ]  Go to page 1, 2  Next
Author Code Snippet
 Code subject: Read your gmail using Java code
PostPosted: Sat Nov 27, 2010 9:34 pm 
Offline
Mastermind
User avatar

Joined: Tue Mar 27, 2007 10:55 pm
Posts: 2279
Location: Earth
Has thanked: 39 time
Have thanks: 61 time

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

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


_________________
Currenlty programming with : java , html , php , and javascript . (OCJP-6 certified )


TOP
 Profile Send private message  
Reply with quote  
 Code subject: Re: Read your gmail using Java code
PostPosted: Tue Oct 18, 2011 7:45 am 
Thanks for this code. How can i read only the unread mails?


TOP
  
Reply with quote  
 Code subject: Re: Read your gmail using Java code
PostPosted: Wed Oct 26, 2011 12:50 pm 
Offline
Mastermind
User avatar

Joined: Tue Mar 27, 2007 10:55 pm
Posts: 2279
Location: Earth
Has thanked: 39 time
Have thanks: 61 time
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);
        }

 

_________________
Currenlty programming with : java , html , php , and javascript . (OCJP-6 certified )


TOP
 Profile Send private message  
Reply with quote  
 Code subject: Re: Read your gmail using Java code
PostPosted: Tue Jan 31, 2012 12:36 pm 
what is this ConfigurationData


TOP
  
Reply with quote  
 Code subject: Re: Read your gmail using Java code
PostPosted: Wed Feb 01, 2012 2:23 am 
Offline
Mastermind
User avatar

Joined: Tue Mar 27, 2007 10:55 pm
Posts: 2279
Location: Earth
Has thanked: 39 time
Have thanks: 61 time
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;
    }
}
 

_________________
Currenlty programming with : java , html , php , and javascript . (OCJP-6 certified )


TOP
 Profile Send private message  
Reply with quote  
 Code subject: Re: Read your gmail using Java code
PostPosted: 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)


TOP
  
Reply with quote  
 Code subject: Re: Read your gmail using Java code
PostPosted: 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", "nithinj3@gmail.com", "nithinj3@gmail.com");

}
}


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:


TOP
  
Reply with quote  
 Code subject: Re: Read your gmail using Java code
PostPosted: Fri Mar 16, 2012 10:17 am 
Offline
Mastermind
User avatar

Joined: Tue Mar 27, 2007 10:55 pm
Posts: 2279
Location: Earth
Has thanked: 39 time
Have thanks: 61 time
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


_________________
Currenlty programming with : java , html , php , and javascript . (OCJP-6 certified )


TOP
 Profile Send private message  
Reply with quote  
 Code subject: Re: Read your gmail using Java code
PostPosted: Fri Mar 23, 2012 7:43 am 
Can you post the whole code or link to your project.


TOP
  
Reply with quote  
 Code subject: Re: Read your gmail using Java code
PostPosted: Thu Apr 05, 2012 6:01 am 
pls post the gui logger class code


TOP
  
Reply with quote  
Post new topic Reply to topic Quick reply  [ 13 posts ]  Go to page 1, 2  Next
Quick reply


  

 Similar topics
 video chat application in java
 navigating to database using java
 java mobile apps
 need help in java
 Java Programing to communicating port parallel
 Code to open multiple links.
 I need help with checkers code
 Java Chat
 Steganography in java
 java code for listing folder contents from remote folder

All times are UTC [ DST ]


Users browsing similar codes

Users browsing this forum: Google Adsense [Bot] and 3 guests



Jump to:  
Previous Code Snippet | Next Code Snippet 




Home
General Talks
Finished Projects
Code Library
Games
Tutorials

Java
C/C++
C-sharp
php
Script
JSP/Servlets
Ajax
ASP/ASP.net
Google SEO
Database
Communications
Phpbb3 styles
Photoshop tutorials
Flash tutorials
Find a job






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team