2010-07-31 7 views
2

Java 코드에서 내 Gmail 계정의 이메일을 가져오고 싶습니다. 어떻게이 일을 할 수 있습니까?Java 애플리케이션에서 내 Gmail 이메일에 액세스하려면 어떻게해야합니까?

+0

안녕하세요,이 숙제입니까? –

+0

[Gmail에서 IMAP을 사용하여 Java 응용 프로그램으로 메일 가져 오기] (http://stackoverflow.com/questions/61176/getting-mail-from-gmail-into-java-application-using-imap) –

+0

검색 창 오른쪽 상단에 있습니다. –

답변

1

Gmail은 Javamail에서 사용할 수있는 IMAP을 사용합니다. 구현시이를 사용하려고 시도하고 막히면 좀 더 구체적인 질문을 게시하십시오.

+0

링크가 현재 고장났습니다. – palacsint

+1

고정, 감사합니다 .. –

1

또 다른 옵션 : Gmail 전용 솔루션 인 경우 Gmail은 사서함에 RSS 피드를 제공하므로 일반 XML 처리 API로 액세스 할 수 있습니다.

0

다음은 POST OFFICE PROTOCOL (pop3)을 사용하여 Gmail 계정에서 첨부 파일 (있는 경우)을 가져 오는 코드입니다.

import com.sun.mail.pop3.POP3Folder; 
import com.sun.mail.pop3.POP3SSLStore; 

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


public class MailfetchingPop3 
{ 
    private Session session; 
    private POP3SSLStore store; 
    private String username; 
    private String password; 
    private POP3Folder folder; 
    public static String numberOfFiles = null; 
    public static int toCheck = 0; 
    public static Writer output = null; 
    URLName url; 
    public static String receiving_attachments="C:\\download"; 

    public MailfetchingPop3() 
    { 
     session = null; 
     store = null; 
    } 

    public void setUserPass(String username, String password) 
    { 
     this.username = username; 
     this.password = password; 
    } 

    public void connect() 
    throws Exception 
    { 
     String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 
     Properties pop3Props = new Properties(); 
     pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); 
     pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); 
     pop3Props.setProperty("mail.pop3.port", "995"); 
     pop3Props.setProperty("mail.pop3.socketFactory.port", "995"); 
     url = new URLName("pop3", "pop.gmail.com", 995, "", username, password); 
     session = Session.getInstance(pop3Props, null); 
     store = new POP3SSLStore(session, url); 
     store.connect(); 
    } 

    public void openFolder(String folderName) 
    throws Exception 
    { 
     folder = (POP3Folder)store.getFolder(folderName); 
     System.out.println((new StringBuilder("For test----")).append(folder.getParent().getFullName()).toString()); 
     if(folder == null) 
      throw new Exception("Invalid folder"); 
     try 
     { 
      folder.open(2); 
      System.out.println((new StringBuilder("Folder name----")).append(folder.getFullName()).toString()); 
     } 
     catch(Exception ex) 
     { 
      System.out.println((new StringBuilder("Folder Opening Exception..")).append(ex).toString()); 
     } 
    } 

    public void closeFolder() 
    throws Exception 
    { 
     folder.close(false); 
    } 

    public int getMessageCount() 
    throws Exception 
    { 
     return folder.getMessageCount(); 
    } 

    public int getNewMessageCount() 
    throws Exception 
    { 
     return folder.getNewMessageCount(); 
    } 

    public void disconnect() 
    throws Exception 
    { 
     store.close(); 
    } 

    public void printAllMessages() 
    throws Exception 
    { 
     Message msgs[] = folder.getMessages(); 
     FetchProfile fp = new FetchProfile(); 
     folder.fetch(msgs, fp); 
     for(int i = 0; i < msgs.length; i++) 
      dumpEnvelope(msgs[i]); 

    } 



    public static int saveFile(File saveFile, Part part) throws Exception { 

     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveFile)); 

     byte[] buff = new byte[2048]; 
     InputStream is = part.getInputStream(); 
     int ret = 0, count = 0; 
     while((ret = is.read(buff)) > 0){ 
      bos.write(buff, 0, ret); 
      count += ret; 
     } 
     bos.close(); 
     is.close(); 
     return count; 
    } 

    private static void dumpEnvelope(Message m) throws Exception 
    { 
     String body=""; 
     String path=""; 
     int size=0; 
     Object content = m.getContent(); 
     if(content instanceof String){ 
      body = (String)content; 
     } 
     else if(content instanceof Multipart) 
     { 
      Multipart mp = (Multipart)content; 
      for (int j=0; j < mp.getCount(); j++) 
      { 
       Part part = mp.getBodyPart(j); 
       String disposition = part.getDisposition(); 
       //System.out.println("test disposition---->>"+disposition); 
       if (disposition == null) { 
        // Check if plain 
        MimeBodyPart mbp = (MimeBodyPart)part; 
        if (mbp.isMimeType("text/plain")) { 
         body += mbp.getContent().toString(); 
        } 
        else if (mbp.isMimeType("TEXT/HTML")) { 
         body += mbp.getContent().toString(); 
        } 
        else { 
         //unknown 
        } 
       } else if ((disposition != null) && 
         (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) || disposition.equals("ATTACHMENT") || disposition.equals("INLINE"))) 
       { 
        // Check if plain 
        MimeBodyPart mbp = (MimeBodyPart)part; 
        if (mbp.isMimeType("text/plain")) { 
         body += (String)mbp.getContent(); 
        } 
        else if (mbp.isMimeType("TEXT/HTML")) { 
         body += mbp.getContent().toString(); 
        } 
        else { 
         File savedir = new File(receiving_attachments); 
         savedir.mkdirs(); 
         File savefile = new File(savedir+"\\"+part.getFileName()); 
         path = savefile.getAbsolutePath(); 
         size = saveFile(savefile, part); 

        } 
       } 
      } 
     } 

    } 
    public static void main(String args[]) 
    { 
     try 
     { 
      MailfetchingPop3 gmail = new MailfetchingPop3(); 
      gmail.setUserPass("your_gmail_Id", "your_gmail_mail_id_password"); 
      gmail.connect(); 
      gmail.openFolder("INBOX"); 
      gmail.printAllMessages(); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
      System.exit(-1); 
     } 
    } 



} 

javamail.jar하고 여기에

3

activation.jar이 다운로드되고 또한 첨부 파일과 함께 적절한 형식으로 콘솔에서 이메일 MSG를 표시 새로 고침 작업 코드입니다 다운로드하기 위해 필요한이 자바 클래스를 실행하려면 ....

import com.sun.mail.pop3.POP3Folder; 
import com.sun.mail.pop3.POP3SSLStore; 

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


public class MailfetchingPop3 
{ 
    private Session session; 
    private POP3SSLStore store; 
    private String username; 
    private String password; 
    private POP3Folder folder; 
    public static String numberOfFiles = null; 
    public static int toCheck = 0; 
    public static Writer output = null; 
    URLName url; 
    public static String receiving_attachments="C:\\download"; 

    public MailfetchingPop3() 
    { 
     session = null; 
     store = null; 
    } 

    public void setUserPass(String username, String password) 
    { 
     this.username = username; 
     this.password = password; 
    } 

    public void connect() 
    throws Exception 
    { 
     String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 
     Properties pop3Props = new Properties(); 
     pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); 
     pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); 
     pop3Props.setProperty("mail.pop3.port", "995"); 
     pop3Props.setProperty("mail.pop3.socketFactory.port", "995"); 
     url = new URLName("pop3", "pop.gmail.com", 995, "", username, password); 
     session = Session.getInstance(pop3Props, null); 
     store = new POP3SSLStore(session, url); 
     store.connect(); 
    } 

    public void openFolder(String folderName) 
    throws Exception 
    { 
     folder = (POP3Folder)store.getFolder(folderName); 
     System.out.println((new StringBuilder("For test----")).append 
(folder.getParent().getFullName()).toString()); 
     if(folder == null) 
      throw new Exception("Invalid folder"); 
     try 
     { 
      folder.open(2); 
      System.out.println((new StringBuilder("Folder name----")).append 
(folder.getFullName()).toString()); 
     } 
     catch(Exception ex) 
     { 
      System.out.println((new StringBuilder("Folder Opening Exception..")).append(ex).toString()); 
     } 
    } 

    public void closeFolder() 
    throws Exception 
    { 
     folder.close(false); 
    } 

    public int getMessageCount() 
    throws Exception 
    { 
     return folder.getMessageCount(); 
    } 

    public int getNewMessageCount() 
    throws Exception 
    { 
     return folder.getNewMessageCount(); 
    } 

    public void disconnect() 
    throws Exception 
    { 
     store.close(); 
    } 

    public void printAllMessages() 
    throws Exception 
    { 
     Message msgs[] = folder.getMessages(); 
     FetchProfile fp = new FetchProfile(); 
     folder.fetch(msgs, fp); 
     for(int i = 0; i < msgs.length; i++){ 
      Message message = msgs[i]; 
      dumpEnvelope(msgs[i]); 
     System.out.println("=============================="); 
    System.out.println("Email #" + (i + 1)); 
    System.out.println("Subject: " + message.getSubject()); 
    System.out.println("From: " + message.getFrom()[0]); 
    System.out.println("Text: " + message.getContent().toString()); 
     } 
    } 



    public static int saveFile(File saveFile, Part part) throws Exception { 

     BufferedOutputStream bos = new BufferedOutputStream(new 
FileOutputStream(saveFile)); 

     byte[] buff = new byte[2048]; 
     InputStream is = part.getInputStream(); 
     int ret = 0, count = 0; 
     while((ret = is.read(buff)) > 0){ 
      bos.write(buff, 0, ret); 
      count += ret; 
     } 
     bos.close(); 
     is.close(); 
     return count; 
    } 

    private static void dumpEnvelope(Message m) throws Exception 
    { 
     String body=""; 
     String path=""; 
     int size=0; 
     Object content = m.getContent(); 
     if(content instanceof String){ 
      body = (String)content; 
     } 
     else if(content instanceof Multipart) 
     { 
      Multipart mp = (Multipart)content; 
      for (int j=0; j < mp.getCount(); j++) 
      { 
       Part part = mp.getBodyPart(j); 
       String disposition = part.getDisposition(); 
       //System.out.println("test disposition---->>"+disposition); 
       if (disposition == null) { 
        // Check if plain 
        MimeBodyPart mbp = (MimeBodyPart)part; 
        if (mbp.isMimeType("text/plain")) { 
         body += mbp.getContent().toString(); 
        } 
        else if (mbp.isMimeType("TEXT/HTML")) { 
         body += mbp.getContent().toString(); 
        } 
        else { 
         //unknown 
        } 
       } else if ((disposition != null) && 
         (disposition.equals(Part.ATTACHMENT) || disposition.equals 
(Part.INLINE) || disposition.equals("ATTACHMENT") || disposition.equals 
("INLINE"))) 
       { 
        // Check if plain 
        MimeBodyPart mbp = (MimeBodyPart)part; 
        if (mbp.isMimeType("text/plain")) { 
         body += (String)mbp.getContent(); 
        } 
        else if (mbp.isMimeType("TEXT/HTML")) { 
         body += mbp.getContent().toString(); 
        } 
        else { 
         File savedir = new File(receiving_attachments); 
         savedir.mkdirs(); 
         File savefile = new File(savedir+"\\"+part.getFileName()); 
         path = savefile.getAbsolutePath(); 
         size = saveFile(savefile, part); 

        } 
       } 
      } 
     } 

    } 
    public static void main(String args[]) 
    { 
     try 
     { 
      MailfetchingPop3 gmail = new MailfetchingPop3(); 
      gmail.setUserPass("your-gmail-username", "your-gmail-password"); 
      gmail.connect(); 
      gmail.openFolder("INBOX"); 
      gmail.printAllMessages(); 

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



} 
관련 문제