1

我正在尝试开发一个应用程序来发送来自特定电子邮件 ID 的电子邮件。它不会执行并强制关闭,为什么会这样?有什么方法可以发送电子邮件,请查看我的代码。

public class MainActivity extends Activity {
    Button send = null;
    EditText mailid = null
    String emailId = null;
    ConnectivityManager conMan = null;
    NetworkInfo Info = null;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        send = (Button)findViewById(R.id.button1);
        mailid = (EditText)findViewById(R.id.editText1);
        send.setOnClickListener(new OnClickListener() {
             @Override
             public void onClick(View arg0) {
                // TODO Auto-generated method stub
                conMan = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                Info = conMan.getActiveNetworkInfo();
                emailId = mailid.getText().toString();

                if (Info == null) {
                    Toast.makeText(getApplicationContext(), "no net connection ", Toast.LENGTH_LONG).show();
                } else {
                    try {
                        GmailSender sender = new GmailSender("karuna.java@gmail.com", "heohiby");
                        sender.sendMail("This is Subject",
                            "This is Body how r u ..",
                            "karuna.java@gmail.com",
                            emailId);
                    } catch (Exception e) {
                        Log.e("SendMail", e.getMessage(), e);
                    }
                }
            }
        });
    }

}

这里是 GmailSender

public class GmailSender extends javax.mail.Authenticator {
    private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;
    static {
        Security.addProvider(new com.provider.JSSEProvider());
    }

    public GmailSender(String user, String password) {
        this.user = user;
        this.password = password;

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        session = Session.getDefaultInstance(props, this);
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }

    public synchronized void sendMail(String subject, String body, String sender, String recipients)throws Exception {
        try {
            MimeMessage message = new MimeMessage(session);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
            message.setSender(new InternetAddress(sender));
            message.setSubject(subject);
            message.setDataHandler(handler);
            if (recipients.indexOf(',') > 0)
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
            else
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
            Transport.send(message);
        } catch (Exception e) {}
    }

    public class ByteArrayDataSource implements DataSource {
        private byte[]data;
        private String type;

        public ByteArrayDataSource(byte[]data, String type) {
            super();
            this.data = data;
            this.type = type;
        }

        public ByteArrayDataSource(byte[]data) {
            super();
            this.data = data;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }

        public InputStream getInputStream()throws IOException {
            return new ByteArrayInputStream(data);
        }

        public String getName() {
            return "ByteArrayDataSource";
        }

        public OutputStream getOutputStream()throws IOException {
            throw new IOException("Not Supported");
        }
    }
}

和提供者

public final class JSSEProvider extends Provider {

    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction < Void > () {
            public Void run() {
                put("SSLContext.TLS",
                    "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                    "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                put("TrustManagerFactory.X509",
                    "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                return null;
            }
        });
    }
}

日志文件

12-19 11:07:43.363: E/AndroidRuntime(977):    at dalvik.system.NativeStart.main(Native Method) 
12-19 11:10:55.453: D/AndroidRuntime(1035): Shutting down VM 
12-19 11:10:55.453: W/dalvikvm(1035): threadid=1: thread exiting with uncaught exception (group=0x40015578) 
12-19 11:10:55.464: E/AndroidRuntime(1035): FATAL EXCEPTION: main 
12-19 11:10:55.464: E/AndroidRuntime(1035): java.lang.NoClassDefFoundError: com.yakshna.mail.GmailSender 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at com.yakshna.mail.MainActivity$1.onClick(MainActivity.java:42) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at android.view.View.performClick(View.java:2538) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at android.view.View$PerformClick.run(View.java:9152) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at android.os.Handler.handleCallback(Handler.java:587) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at android.os.Handler.dispatchMessage(Handler.java:92) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at android.os.Looper.loop(Looper.java:123) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at android.app.ActivityThread.main(ActivityThread.java:3687) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at java.lang.reflect.Method.invokeNative(Native Method) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at java.lang.reflect.Method.invoke(Method.java:507) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
12-19 11:10:55.464: E/AndroidRuntime(1035):     at dalvik.system.NativeStart.main(Native Method) 
12-19 11:11:02.570: I/Process(1035): Sending signal. PID: 1035 SIG: 9

此处显示错误:

GmailSender sender = new GmailSender("karuna.java@gmail.com", "heohiby");
4

2 回答 2

3

您目前的问题是您尚未<uses-permission>Android.manifest.

getActiveNetworkInfo()方法需要 ACCESS_NETWORK_STATE权限。

你需要把它放在你的Android.manifest文件中

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

于 2012-12-18T14:43:10.497 回答
1

清单中的权限是否正确?

也请务必阅读:

http://productforums.google.com/forum/#!msg/gmail/XD0C4sw9K7U/LpNXxFNnfgc

以前的权限是:

?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="googlecode.email.to.sms" android:versionCode="2"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".Email2SMSActivity" 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>
<uses-sdk android:minSdkVersion="5" 
    android:maxSdkVersion="8"
    android:targetSdkVersion="7" />

<uses-permission
    android:name="com.google.android.providers.gmail.permission.READ_GMAIL" />
<uses-permission
    android:name="com.google.android.gm.permission.READ_GMAIL" />
<uses-permission 
    android:name="android.permission.GET_ACCOUNTS" />
</manifest> 

我在 Android 中没有使用过 Gmail,但希望这会有所帮助。

于 2012-12-18T14:45:34.653 回答