1

I'm trying to develop an application to send an email from a specific email id. it won't execute and force close, why so ? And Is there any way to send email please have a look on my code.

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

}

here the 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");
        }
    }
}

and the provider

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

log file

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

shows error here:

GmailSender sender = new GmailSender("karuna.java@gmail.com", "heohiby");
Tuan
  • 2,883
  • 4
  • 32
  • 54
Bamadeva
  • 327
  • 2
  • 9
  • 21
  • 2
    java.lang.SecurityException: ConnectivityService: Neither user 10075 nor current process has android.permission.ACCESS_NETWORK_STATE – David M Dec 18 '12 at 14:37
  • Try setting the session.setDebug(true); And check whether its even going in GMailSender.java or not! Because logcat error shows: "java.lang.NoClassDefFoundError: com.yakshna.mail.GmailSender" . And once try downloading the jar files from other site and adding them. – MysticMagicϡ Dec 19 '12 at 06:29
  • When you edit your posts please write what has changed in the edit. Now there are 2 answers and both of them are irrelevant to your question because when your question changed you removed the previous explanation – jankovd Dec 19 '12 at 11:49

2 Answers2

3

Your problem at the moment is that you haven't declared a <uses-permission> in the Android.manifest.

The method getActiveNetworkInfo() requieres ACCESS_NETWORK_STATE permission.

You need to put this in your Android.manifest file

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

jankovd
  • 1,583
  • 15
  • 21
  • I did this still not working. The same problem of crashing my app. – Bamadeva Dec 19 '12 at 05:46
  • But it's not the same problem. [This SO thread](http://stackoverflow.com/a/9916751/471073) and [this post](http://android.foxykeep.com/dev/how-to-fix-the-classdefnotfounderror-with-adt-17) might help you if you're using an external library and that causes the crash – jankovd Dec 19 '12 at 11:12
1

Are the correct permissions in the manifest?

also be sure to read this:

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

the permissions used to be:

?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> 

I haven't worked with Gmail in a few in Android but hopefully this will help.

Sean
  • 196
  • 11