Can not send mail from the Android app using the Java Mail API

advertisements

i am trying to send an email from my android app using java mail api, when i run the code in java project it sends mail successfully but when i use this code into android app, logcat shows error as follows :-

09-03 15:18:57.549: ERROR/AndroidRuntime(277): FATAL EXCEPTION: main

09-03 15:18:57.549: ERROR/AndroidRuntime(277): java.lang.RuntimeException: Unable to start activity ComponentInfo{email3.app/email3.app.email3}: java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;

09-03 15:18:57.549: ERROR/AndroidRuntime(277): java.net.SocketException: Permission denied

the code is as follows :-

file1 :- email3.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

 public class email3 extends Activity {
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    sender s=new sender();

    }
}

file 2 :- sender.java

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;  

public class sender {
 public sender() {  

 String to="[email protected]";//change accordingly  

  //Get the session object
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");  

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]","yyy");//change accordingly
}
});  

//compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));//change accordingly
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Hello");
message.setText("Testing.......");  

//send message
Transport.send(message);  

} catch (MessagingException e) {throw new RuntimeException(e);}  

}
}  

file :- 3  Menifest file

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".email3"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
<uses-permission android:name="android.permission.INTERNET" />
</application>


If you're using the "smtps" protocol to access SMTP over SSL, all the properties would be named "mail.smtps.*"

Use props.put("mail.smtp.port", "888"); to set the mail.smtp.port property, which is of type int.