在后台发送电子邮件 - Android

时间:2013-01-16 23:58:59

标签: java android email

我有这个代码,两个简单的类:一个邮件发件人和只有一个按钮的主要Android活动。这是活动代码:

package com.py.spycam;

import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.internet.AddressException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void onClickMail(View v) {
        String[] to = {"toaddress"};
        SMTPMail mail = new SMTPMail("user", "pass");
        try {
            mail.send("sender", to, "prova", "prova bpdy");
            Toast.makeText(this, "Mail sent", Toast.LENGTH_SHORT).show();
        } catch (NoSuchProviderException e) {
            Toast.makeText(this, "Unable to send email (NoSuchProviderException)", Toast.LENGTH_SHORT).show();
        } catch (AddressException e) {
            Toast.makeText(this, "Unable to send email (AddressException)", Toast.LENGTH_SHORT).show();
        } catch (MessagingException e) {
            Toast.makeText(this, "Unable to send email (MessagingException)", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "Unable to send email (general Exception)", Toast.LENGTH_SHORT).show();
        }

    }

}

这是邮件发件人:

package com.py.spycam;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SMTPMail {
    private String host;
    private String from;
    private String pass;
    private Properties props;

    public SMTPMail(String _user, String _pass) {
        host = "smtp.gmail.com";
        from = _user;
        pass = _pass;
        props = System.getProperties();

        /* Props settings */
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
    }

    public void send(String from, String[] to, String subject, String body)
            throws AddressException, MessagingException, NoSuchProviderException {
            //throws AddressException, MessagingException {

        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for(int i=0; i < to.length; i++ ) { // changed from a while loop
            toAddress[i] = new InternetAddress(to[i]);
        }

        for(int i=0; i < toAddress.length; i++) { // changed from a while loop
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }
        message.setSubject(subject);
        message.setText(body);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }


}

我一直得到一个普通的异常,没有被任何catch语句捕获(怎么可能?从哪里抛出?)。这段代码出了什么问题? 注意:如果使用普通Java(javac编译,使用简单的main执行)执行此代码,则此代码有效。

Mega-edit:这是LogCat的输出,仅限于System.err警告(从printStackTrace()生成。

01-17 01:41:41.550: W/System.err(23420): android.os.NetworkOnMainThreadException
01-17 01:41:41.550: W/System.err(23420):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
01-17 01:41:41.555: W/System.err(23420):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-17 01:41:41.555: W/System.err(23420):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-17 01:41:41.555: W/System.err(23420):    at java.net.InetAddress.getByName(InetAddress.java:289)
01-17 01:41:41.555: W/System.err(23420):    at java.net.InetSocketAddress.<init>(InetSocketAddress.java:105)
01-17 01:41:41.555: W/System.err(23420):    at java.net.InetSocketAddress.<init>(InetSocketAddress.java:90)
01-17 01:41:41.555: W/System.err(23420):    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
01-17 01:41:41.555: W/System.err(23420):    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
01-17 01:41:41.555: W/System.err(23420):    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
01-17 01:41:41.555: W/System.err(23420):    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
01-17 01:41:41.555: W/System.err(23420):    at javax.mail.Service.connect(Service.java:288)
01-17 01:41:41.560: W/System.err(23420):    at javax.mail.Service.connect(Service.java:169)
01-17 01:41:41.560: W/System.err(23420):    at com.py.spycam.SMTPMail.send(SMTPMail.java:55)
01-17 01:41:41.560: W/System.err(23420):    at com.py.spycam.MainActivity.onClickMail(MainActivity.java:29)
01-17 01:41:41.560: W/System.err(23420):    at java.lang.reflect.Method.invokeNative(Native Method)
01-17 01:41:41.560: W/System.err(23420):    at java.lang.reflect.Method.invoke(Method.java:511)
01-17 01:41:41.560: W/System.err(23420):    at android.view.View$1.onClick(View.java:3586)
01-17 01:41:41.560: W/System.err(23420):    at android.view.View.performClick(View.java:4084)
01-17 01:41:41.560: W/System.err(23420):    at android.view.View$PerformClick.run(View.java:16966)
01-17 01:41:41.560: W/System.err(23420):    at android.os.Handler.handleCallback(Handler.java:615)
01-17 01:41:41.560: W/System.err(23420):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-17 01:41:41.565: W/System.err(23420):    at android.os.Looper.loop(Looper.java:137)
01-17 01:41:41.565: W/System.err(23420):    at android.app.ActivityThread.main(ActivityThread.java:4931)
01-17 01:41:41.565: W/System.err(23420):    at java.lang.reflect.Method.invokeNative(Native Method)
01-17 01:41:41.565: W/System.err(23420):    at java.lang.reflect.Method.invoke(Method.java:511)
01-17 01:41:41.565: W/System.err(23420):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
01-17 01:41:41.565: W/System.err(23420):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
01-17 01:41:41.565: W/System.err(23420):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:3)

非常基本。

android线程模型有两个规则。

1)不要阻止主线程。 2)不要操纵另一个线程的主(“UI”)线程

您通过对其进行网络调用来阻止主线程,从而违反了其中的第一个。将发送邮件移动到其他线程。考虑一个简单的线程或AsyncTask

另外,请参阅有关"Processes and Threads"的开发者文档。

另外,请注意,您似乎目前已启用StrictMode,这是一件好事。这会检测您“不应该”执行的操作,例如在主线程上进行网络调用,如果这样做则会抛出异常。