简体   繁体   English

如何从Java应用程序访问我的Gmail电子邮件?

[英]How can I access my gmail emails from a Java application?

I want to fetch the emails of my gmail account from Java code. 我想从Java代码中获取我的gmail帐户的电子邮件。 How can I go about doing this? 我该怎么做呢?

Here is the Refresh Working Code, that Displays the Email msgs in the console in a proper format along with the Attachments also being Downloaded.... 这是刷新工作代码,它以适当的格式在控制台中显示电子邮件消息,以及附件也正在下载中。...

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



}

Gmail uses IMAP, which Javamail can use. Gmail使用IMAP,而Javamail可以使用IMAP。 Try to use that in an implementation, and if you get stuck, post some more specific questions here. 尝试在实现中使用它,如果遇到麻烦,请在此处发布一些更具体的问题。

另一个选择:如果您不介意它是Gmail特定的解决方案,请注意,Gmail还为您的邮箱提供了RSS供稿,然后您可以使用常规XML处理API对其进行访问。

Here is the code which fetch mail along with it's attachments (if any) from a gmail account using POST OFFICE PROTOCOL (pop3) . 这是使用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);
        }
    }



}

To run this java class you need to download javamail.jar and activation.jar 要运行此Java类,您需要下载javamail.jaractivation.jar

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Gmail下载包含附件的所有电子邮件? - How can I download all emails with attachments from Gmail? 如何为从 Gmail 服务器读取电子邮件的 Java 应用程序设计故障转移 - How to design fail over for Java application which is reading emails from Gmail Server 从我的 Java 应用程序调用 getQueryResults 方法时,如何从 QueryResponse 访问架构? - How can I access Schema from the QueryResponse while calling getQueryResults method from my Java application? 如何在Java Web应用程序中访问Heroku ClearDB? - How can I access Heroku ClearDB in my Java web application? 如何查看来自我的Android应用程序的已发送电子邮件? 还是打算完成(无论发送了什么电子邮件)? - How can I check sent emails from my Android application? Or intent upon completion (regardless of email sent)? 如何使用gmail从Spring应用程序发送电子邮件? - How to send emails from spring application using gmail? 我可以在Java应用程序中通过POP3和OAuth2访问Gmail邮件吗? - Can I access Gmail mails by POP3 and OAuth2 in Java application? 在Android中,如何使用Java从我自己的应用程序访问Google Calendar(在线)事件数据? - In Android, How can I access Google Calendar's (online) events data from my own application using Java? Yahoo和Gmail未收到从Java发送的电子邮件 - Emails sent from Java not received at Yahoo & Gmail 如何在GAE访问gmail? - How I can access gmail at GAE?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM