在android中接收/阅读电子邮件

时间:2015-01-19 06:40:26

标签: java android email

我是android的新手。我想构建一个应用程序来接收&从我自己的应用程序中读取电子邮件。我在这些链接的帮助下准备了我的代码。一些博客。

Retrieving all unread emails using javamail with POP3 protocol

https://buddhimawijeweera.wordpress.com/2011/02/09/sendreceiveemailsjava/

https://metoojava.wordpress.com/2010/03/21/java-code-to-receive-mail-using-javamailapi/

我已经工作了将近两个星期,但仍然应用程序没有显示收到的电子邮件。请帮我查找错误。或者你知道一个代码将Gmail应用程序与我的应用程序连接以接收电子邮件吗?非常感谢您对该应用程序的任何帮助。

MailReaderActivity.java(主要活动)

public class MailReaderActivity extends Activity{

    Folder inbox;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);


    }

    public MailReaderActivity(){

        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        try {

            Session session = Session.getDefaultInstance(props, null);
            Store store;
            store = session.getStore("imaps");
            store.connect("imap.gmail.com","<user@gmail.com>","<password>");

            inbox = store.getFolder("Inbox");
            System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());

            inbox.open(Folder.READ_ONLY);

            Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));

            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.CONTENT_INFO);
            inbox.fetch(messages, fp);

            try {
                printAllMessages(messages);
                inbox.close(true);
                store.close();
            } catch (Exception ex) {
                System.out.println("Exception arise at the time of read mail");
                ex.printStackTrace();
            }
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (MessagingException e) {
            e.printStackTrace();
            System.exit(2);
        }
    }


    public void printAllMessages(Message[] msgs) throws Exception
    {
        for (int i = 0; i < msgs.length; i++)
        {
            System.out.println("MESSAGE #" + (i + 1) + ":");
            printEnvelope(msgs[i]);
        }
    }
    public void printEnvelope(Message message) throws Exception
    {
        Address[] a;
        // FROM
        if ((a = message.getFrom()) != null)
        {
            for (int j = 0; j < 2; j++)
            {
                System.out.println("FROM: " + a[j].toString());
            }
        }
        // TO
        if ((a = message.getRecipients(Message.RecipientType.TO)) != null)
        {
            for (int j = 0; j < 2; j++)
            {
                System.out.println("TO: " + a[j].toString());
            }
        }
        String subject = message.getSubject();
        Date receivedDate = message.getReceivedDate();
        String content = message.getContent().toString();
        System.out.println("Subject : " + subject);
        System.out.println("Received Date : " + receivedDate.toString());
        System.out.println("Content : " + content);
        getContent(message);
    }

    public void getContent(Message msg)
    {
        try
        {
            String contentType = msg.getContentType();
            System.out.println("Content Type : " + contentType);
            Multipart mp = (Multipart) msg.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++)
            {
                dumpPart(mp.getBodyPart(i));
            }
        }
        catch (Exception ex)
        {
            System.out.println("Exception arise at get Content");
            ex.printStackTrace();
        }
    }

    public void dumpPart(Part p) throws Exception
    {
        // Dump input stream ..
        InputStream is = p.getInputStream();
        // If "is" is not already buffered, wrap a BufferedInputStream
        // around it.
        if (!(is instanceof BufferedInputStream))
        {
            is = new BufferedInputStream(is);
        }
        int c;
        System.out.println("Message : ");
        while ((c = is.read()) != -1)
        {
            System.out.write(c);
        }
    }

    public static void main(String args[])
    {
        new MailReaderActivity();
    }
}

的Manifest.xml

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MailReaderActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Logcat

 //01-19 13:09:00.554    8487-8487/com.example.dell.frfr E/Trace﹕ error opening trace file: No such file or directory (2)
01-19 13:09:00.812    8487-8487/com.example.dell.frfr E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.dell.frfr/com.example.dell.frfr.MailReaderActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
            at java.net.InetAddress.getByName(InetAddress.java:289)
            at java.net.InetSocketAddress.<init>(InetSocketAddress.java:105)
            at java.net.InetSocketAddress.<init>(InetSocketAddress.java:90)
            at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
            at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
            at com.sun.mail.iap.Protocol.<init>(Protocol.java:116)
            at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:115)
            at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:685)
            at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:636)
            at javax.mail.Service.connect(Service.java:295)
            at javax.mail.Service.connect(Service.java:176)
            at com.example.dell.frfr.MailReaderActivity.<init>(MailReaderActivity.java:53)
            at java.lang.Class.newInstanceImpl(Native Method)
            at java.lang.Class.newInstance(Class.java:1319)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1123)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2268)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
            at android.app.ActivityThread.access$600(ActivityThread.java:165)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
            at android.os.Handler.dispatchMessage(Handler.java:107)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5370)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)
//

2 个答案:

答案 0 :(得分:0)

我不知道您是否已经修复了这个错误,但如果我仍然回答它,它可能会帮助有类似问题的人。

在您的LogCat中。它说Caused by: android.os.NetworkOnMainThreadException Android默认情况下不允许任何网络与应用程序的其余部分在同一个线程上。因此,为了解决这个问题,我们只需创建一个新线程来运行它。

替换:

public static void main(String args[])
    {
        new MailReaderActivity();
    }

用这个:

public static void main(String args[])
{
  Thread thread = new Thread() {
      @Override
      public void run() {
          new MailReaderActivity();
      }
  };

  thread.start();
}

答案 1 :(得分:0)

您应该使用AsyncTask异步执行网络线程。有关更多信息,请阅读the docs