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...");
    }
}

21 comments:

  1. Please I cannot understand your code

    ReplyDelete
  2. If you have knowledge of Java in middle level?

    Then you can only understand my code.

    -Amit

    ReplyDelete
  3. hi Amit,
    You code is simply superb may i know after downloading where the email attachment files are stored.

    ReplyDelete
  4. Arun,

    You can find all the attachments in the current directory of your java file.

    ReplyDelete
  5. Please amit check on the line of the first for loop-not complete. Could you please send the full code on my email address?

    ReplyDelete
  6. Amit I'm making a project that should receive mail and save attachment-for users and am really stuck. Please help me

    ReplyDelete
  7. Amit
    i got the attachment thank you very much. But while reading the body of the content from mail i am getting HTML encoding characters and all can u tell me how to remove that.

    ReplyDelete
  8. Arun,


    Just create a method. In that method you should write a code for remove HTML encoding character.

    ReplyDelete
  9. Kings,


    Just copy and paste listed below article's code.

    http://amitkgaur.blogspot.com/2011/03/read-gmail-email-and-save-attachement.html

    ReplyDelete
  10. Hi Amit,

    I'm trying to not only save the attachments as files instead of saving the whole message as msg-file. I don't mean something like editing it and save it back one the mail-server with saveChanges() or something like that. What I mean is to write a new file .msg on my desktop for example.
    I tryied using:
    OutputStream out = new FileOutputStream(new File(strFilePath));
    msg.writeTo(out);
    ...but this always causes an error when opening the file. I think the format is not set correctly while writing it but I don't really know a solution for this problem or if this really is the problem. Do you?

    ReplyDelete
  11. Mondlotus, your answer is here
    Apache POI http://poi.apache.org/
    and
    http://www.independentsoft.de/jmsg/index.html

    ReplyDelete
  12. hey can u tell me how to save the attachment in any folder in any location

    ReplyDelete
    Replies
    1. Pritam deb, just use the full directory path as listed below:

      saveFile("c:\\temp\\"+part.getFileName(), part.getInputStream());

      Delete
  13. Hey can you provide java code for creating labels and assign a particular label to that mail for gmail

    ReplyDelete
  14. Naresh,

    you can find more about java mail from
    http://www.oracle.com/technetwork/java/javamail/index.html

    ReplyDelete
  15. im getting errors in your code with the integer i in your for loops some saying it doesnt exist and some saying cannot convert from boolean to int.

    ReplyDelete
    Replies
    1. Test1, can you send me the code with your email and password?

      Delete
  16. i am getting errors with the integer i used in the for loops it says cannot convert from boolean to integer.

    ReplyDelete
    Replies
    1. st1, can you send me the code with your email and password?

      Delete
  17. Though millions of people logging Gmail every day, but some may find the Gmail account tricky and tough to handle and at that moment they need Gmail tech support, so to use an error free Gmail account a user can contact on Gmail Support Number at any stretch of the day.
    how to recover gmail deleted emails

    ReplyDelete