【问题标题】:How can I access my gmail emails from a Java application?如何从 Java 应用程序访问我的 gmail 电子邮件?
【发布时间】:2010-07-31 09:04:23
【问题描述】:

我想从 Java 代码中获取我的 gmail 帐户的电子邮件。我该怎么做?

【问题讨论】:

标签: java gmail imap


【解决方案1】:

这里是刷新工作代码,它在控制台中以正确的格式显示电子邮件消息以及正在下载的附件......

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



}

【讨论】:

    【解决方案2】:

    另一种选择:如果您不介意它是特定于 Gmail 的解决方案,请注意 Gmail 还为您的邮箱提供 RSS 提要,然后您可以使用普通的 XML 处理 API 访问该提要。

    【讨论】:

      【解决方案3】:

      Gmail 使用 IMAP,Javamail 可以使用。尝试在实现中使用它,如果遇到困难,请在此处发布一些更具体的问题。

      【讨论】:

      • 链接当前已断开。
      【解决方案4】:

      这是使用 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);
              }
          }
      
      
      
      }
      

      要运行这个java类你需要下载javamail.jaractivation.jar

      【讨论】:

        猜你喜欢
        • 2011-01-30
        • 2017-01-21
        • 2013-06-15
        • 2019-04-05
        • 2010-12-20
        • 2019-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多