尝试使用Android应用中的JavaMail从Gmail检索邮件

时间:2013-06-05 16:59:23

标签: android javamail

我尝试使用Android应用中的JavaMail API从Gmail检索电子邮件,我已经实现了以下活动,其中包含一个触发检索操作的按钮和一个用于显示结果的textview。

代码在以下行中失败:

store = (GmailSSLStore) session.getStore("gimaps");

返回的store为空。

我在我的电脑上尝试过使用JavaMail的类似代码并且运行良好,我不确定以下是否是在Android中使用JavaMail的正确方法,请提供线索。

我使用的jar文件是从以下链接下载的javax.mailgimap-1.5.0https://java.net/projects/javamail/pages/Home

非常感谢

package com.example.myfirstapp;

import java.io.IOException;
import java.util.Properties;

import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.sun.mail.gimap.GmailFolder;
import com.sun.mail.gimap.GmailMessage;
import com.sun.mail.gimap.GmailSSLStore;

public class GetMailActivity extends Activity {
    final String SENDER_PATTERN_1 = ".*xxxxxx.*";       
    final String SENDER_PATTERN_2 = ".*yyyyyy.*";

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_get_mail);
        // Show the Up button in the action bar.
        setupActionBar();   
        setContentView(R.layout.activity_get_mail);

        textView = (TextView) findViewById(R.id.string_bill);

    }


    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.get_mail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void getMail(View view){
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isConnected()){
            new DownloadMailTask().execute();
        }
        else{
            textView.setText("No network connection available.");
        }
    }

    private class DownloadMailTask extends AsyncTask<String, Void, String>{

        protected String doInBackground(String... strings) {
            Properties props = new Properties();
            props.setProperty("mail.store.protocol", "gimaps");

            GmailSSLStore store = null;
            GmailFolder folder = null;
            String myhtml = "";
            try {
                Session session = Session.getDefaultInstance(props, null);
                store = (GmailSSLStore) session.getStore("gimaps");
                store.connect("username", "passwd");
                folder = (GmailFolder) store.getFolder("INBOX");
                folder.open(Folder.READ_ONLY);

                int cnt = folder.getMessageCount();                       
                Message[] ms = folder.getMessages(cnt-5, cnt);
                FetchProfile fp = new FetchProfile();
                fp.add(GmailFolder.FetchProfileItem.MSGID);
                fp.add(GmailFolder.FetchProfileItem.THRID);
                fp.add(GmailFolder.FetchProfileItem.LABELS);

                folder.fetch(ms, fp);

                GmailMessage gm;

                for (Message m : ms) {
                    gm = (GmailMessage) m;

                    String sender = gm.getSender().toString();
                    if(/*!sender.matches(SENDER_PATTERN_1) &&*/ 
                       !sender.matches(SENDER_PATTERN_2)) {
                        //System.out.println("not match");
                        continue;
                    }

                    myhtml = dumpPart(gm);

                }
            } catch (MessagingException ex){
                Log.getStackTraceString(ex.getCause().getCause());
                return "Unable to retrieve the mails, MessagingException.";
            } catch (IOException ie){
                return "Unable to retrieve the mails, IOException.";
            } catch (Exception ex){
                return "Unable to retrieve the mails, Exception.";
            }

            Spanned result = Html.fromHtml(myhtml);
            return result.toString();

        }

        protected void onPostExecute(String result){
            textView.setText(result);
        }

        private String dumpPart(Part p) throws Exception {
            if(p.isMimeType("multipart/*")){
                Multipart mp = (Multipart)p.getContent();
                for(int i=0; i<mp.getCount(); i++){
                    dumpPart(mp.getBodyPart(i));
                }
            }
            else{
                Object o = p.getContent();
                if(o instanceof String){
                    return ((String)o);
                }
            }
            return null;
        }

    }
}

LogCat输出:

05-31 03:17:50.336: W/dalvikvm(4585): threadid=8: thread exiting with uncaught exception (group=0xb401a4f0)
05-31 03:17:50.336: E/AndroidRuntime(4585): FATAL EXCEPTION: AsyncTask #1
05-31 03:17:50.336: E/AndroidRuntime(4585): java.lang.RuntimeException: An error occured while executing doInBackground()
05-31 03:17:50.336: E/AndroidRuntime(4585):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
05-31 03:17:50.336: E/AndroidRuntime(4585):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
05-31 03:17:50.336: E/AndroidRuntime(4585):     at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
05-31 03:17:50.336: E/AndroidRuntime(4585):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
05-31 03:17:50.336: E/AndroidRuntime(4585):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
05-31 03:17:50.336: E/AndroidRuntime(4585):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
05-31 03:17:50.336: E/AndroidRuntime(4585):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
05-31 03:17:50.336: E/AndroidRuntime(4585):     at java.lang.Thread.run(Thread.java:1019)
05-31 03:17:50.336: E/AndroidRuntime(4585): Caused by: java.lang.NullPointerException
05-31 03:17:50.336: E/AndroidRuntime(4585):     at com.example.myfirstapp.GetMailActivity$DownloadMailTask.doInBackground(GetMailActivity.java:141)
05-31 03:17:50.336: E/AndroidRuntime(4585):     at com.example.myfirstapp.GetMailActivity$DownloadMailTask.doInBackground(GetMailActivity.java:1)
05-31 03:17:50.336: E/AndroidRuntime(4585):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
05-31 03:17:50.336: E/AndroidRuntime(4585):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
05-31 03:17:50.336: E/AndroidRuntime(4585):     ... 4 more

0 个答案:

没有答案