Showing posts with label java email attachment. Show all posts
Showing posts with label java email attachment. Show all posts

Sunday, March 20, 2011

Read Gmail email and save attachement in Java

Read GMAIL Email and save attachment in JAVA.

set class path of these jara files mail.jar and activation.jar
and run these piece of code.



import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class GmailMailAttach {
    public static void main (String args[]) throws Exception {
        String host = "pop.gmail.com";
        String username = "amitt800"; //Put here Gmail Username without @ sign
        String password = "123456"; // put here Gmail password
        Session session = Session.getInstance(new Properties(), null);
        Store store = session.getStore("pop3s");
        store.connect(host, username, password);
        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        Message message[] = folder.getMessages();
       Enumeration headers = message[i].getAllHeaders();
       while (headers.hasMoreElements()) {
             Header h = (Header) headers.nextElement();
             System.out.println(h.getName() + ": " + h.getValue());
       }

        for(int i=0, n=message.length; i++) {
            System.out.println(i + ": " + message[i].getFrom()[0]+ "\t" + message[i].getSubject());
            System.out.println("Want to get the content? [Y to read/Q to end]");
            String ans = reader.readLine();
            ans=ans.toLowerCase();
            if ("y".equals(ans)) {
                Object content = message[i].getContent();
                if (content instanceof Multipart) {
                    handleMultipart((Multipart)content);
                }
                else {
                    handlePart(message[i]);
                }
            }
            else if ("q".equals(ans)) {
                break;
            }
        }
        folder.close(false);
        store.close();
    }
    public static void handleMultipart(Multipart multipart) throws MessagingException, IOException {
        for (int i=0, n=multipart.getCount(); i
            handlePart(multipart.getBodyPart(i));
        }
      }
    public static void handlePart(Part part)  throws MessagingException, IOException {
        String dposition = part.getDisposition();
        String cType = part.getContentType();
        if (dposition == null) {
            System.out.println("Null: "  + cType);
            if ((cType.length() >= 10) && (cType.toLowerCase().substring(0, 10).equals("text/plain"))) {
                part.writeTo(System.out);
            }
            else {
                System.out.println("Other body: " + cType);
                part.writeTo(System.out);
            }
        }
        else if (dposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            System.out.println("Attachment: " + part.getFileName() + " : " + cType);
            saveFile(part.getFileName(), part.getInputStream());
        }
        else if (dposition.equalsIgnoreCase(Part.INLINE)) {
            System.out.println("Inline: " + part.getFileName() +  " : " + cType);
            saveFile(part.getFileName(), part.getInputStream());
        }
        else { 
            System.out.println("Other: " + dposition);
        }
    }
   
    public static void saveFile(String filename,InputStream input) throws IOException {
        if (filename == null) {
            filename = File.createTempFile("MailAttacheFile", ".out").getName();
        }
        System.out.println("downloading attachment...");
        File file = new File(filename);
        for (int i=0; file.exists(); i++) {
            file = new File(filename+i);
        }
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        BufferedInputStream bis = new BufferedInputStream(input);
        int fByte;
        while ((fByte = bis.read()) != -1) {
            bos.write(fByte);
            }
        bos.flush();
        bos.close();
        bis.close();
        System.out.println("done attachment...");
    }
}