I wanted my Raspberry PI to read my Emails. So i needed a Java program to to read the mails. Most of the Java programs I found on net were not working due to SSL certificate errors. Finally here i came up with a code that's working amazingly..!! Atleast for now..!!
- import com.sun.mail.util.MailSSLSocketFactory;
- import java.security.GeneralSecurityException;
- import java.util.Properties;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.mail.Folder;
- import javax.mail.Message;
- import javax.mail.Session;
- import javax.mail.Store;
- import javax.mail.internet.InternetAddress;
- public class Downloader {
- public static void main(String[] args) {
- Downloader gmail = new Downloader();
- try {
- gmail.read();
- } catch (GeneralSecurityException ex) {
- Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- public void read() throws GeneralSecurityException {
- MailSSLSocketFactory socketFactory= new MailSSLSocketFactory();
- socketFactory.setTrustAllHosts(true);
- Properties propsSSL = new Properties();
- propsSSL.put("mail.smtp.host", "smtp.gmail.com");
- propsSSL.put("mail.smtp.socketFactory.port", "465");
- propsSSL.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
- propsSSL.put("mail.smtp.port", "465");
- propsSSL.put("mail.imaps.ssl.socketFactory", socketFactory);
- propsSSL.put("mail.smtps.auth", "true");
- propsSSL.put("mail.smtps.ssl.checkserveridentity", "false");
- propsSSL.put("mail.smtps.ssl.trust", "*");
- try {
- Session session = Session.getDefaultInstance(propsSSL, null);
- Store store = session.getStore("imaps");
- store.connect("smtp.gmail.com", "yourmail@gmail.com","password");
- Folder inbox = store.getFolder("inbox");
- inbox.open(Folder.READ_ONLY);
- int messageCount = inbox.getMessageCount();
- System.out.println("Total Messages:- " + messageCount);
- Message[] messages = inbox.getMessages();
- System.out.println("------------------------------");
- for (int i = 0; i < messageCount; i++) {
- System.out.println("Mail Subject:- " + messages[i].getSubject());
- System.out.println("Time: "+messages[i].getSentDate());
- System.out.println("From: " +InternetAddress.toString(messages[i].getFrom())+"\n");
- }
- inbox.close(true);
- store.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Wait, not over yet. You need to allow the google to allow you to access your mails from a less secure device. ie your program..!! Click Here to allow access.
Output:-
Any issues or suggestions: please comment below..!!!


No comments:
Post a Comment