1

I want to send email from my Android application so my code is

public class MainActivity extends Activity  implements OnClickListener{

Session session=null;
ProgressDialog pdialog=null;
Context context=null;
EditText reciept=null;
EditText sub=null;
EditText msg=null;
String recpient=null;
String subject=null;
String textmessage=null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  context=this;
  Button login = (Button) findViewById(R.id.mBtnSubmit);
  reciept=(EditText)findViewById(R.id.editText_to);
  sub = (EditText) findViewById(R.id.editText_sub);
  msg = (EditText) findViewById(R.id.editText_text);


  login.setOnClickListener(this); 


  }

    @Override
    public void onClick(View v) {

        recpient= reciept.getText().toString();
        subject= sub.getText().toString();
        textmessage= msg.getText().toString();

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


          session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication("abc@a.a", "password");
          }
          });
          pdialog = ProgressDialog.show(context, "", "Sending Mail...",true);
          RetreiveFeedTask task= new RetreiveFeedTask();
          task.execute();
    }


  class RetreiveFeedTask extends AsyncTask<String, Void, String> {


      protected String doInBackground(String... urls) {
            try {

                  Message message = new MimeMessage(session);
                  message.setFrom(new InternetAddress("abc@a.a"));
                  message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recpient));
                  message.setSubject(subject);
                  message.setContent(textmessage, "text/html; charset=utf-8");

                  Transport.send(message);


            } 
            catch (MessagingException e) {
                 e.printStackTrace();
                  }
            catch (Exception e) {
               e.printStackTrace();

            }
            return null;
        }

        protected void onPostExecute(String feed) {
            pdialog.dismiss();
            reciept.setText("");
            msg.setText("");
            sub.setText("");
            Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_LONG).show();

        }
  }


}

and i also attach jars like

activation.jar
additionnal.jar
mail.jar
android-support-v4.jar

when i run above code i gave me error like

02-18 16:16:05.242: W/System.err(3242): javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
02-18 16:16:05.242: W/System.err(3242):   nested exception is:
02-18 16:16:05.242: W/System.err(3242):     javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
02-18 16:16:05.242: W/System.err(3242):     at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
02-18 16:16:05.242: W/System.err(3242):     at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
02-18 16:16:05.242: W/System.err(3242):     at javax.mail.Service.connect(Service.java:310)
02-18 16:16:05.242: W/System.err(3242):     at javax.mail.Service.connect(Service.java:169)
02-18 16:16:05.242: W/System.err(3242):     at javax.mail.Service.connect(Service.java:118)
02-18 16:16:05.242: W/System.err(3242):     at javax.mail.Transport.send0(Transport.java:188)

How can I solve it?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Harshal Kalavadiya
  • 2,412
  • 4
  • 38
  • 71

3 Answers3

1
package com.example.maler;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

 import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;

 public class Neamail extends Activity{

Button mButton;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mButton=(Button)findViewById(R.id.button1);
     StrictMode.ThreadPolicy policy = 
                new  StrictMode.ThreadPolicy.Builder().permitAll().build();      
                    StrictMode.setThreadPolicy(policy);
    mButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                sendEmail();
            } catch (AddressException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}
public void sendEmail() throws AddressException, MessagingException {
    String host = "smtp.gmail.com";
    String address = "senderaddress@gmail.com";

    String from = "senderaddress@gmail.com";
    String pass = "sender pass";
    String to="receiver@address.com";

    Multipart multiPart;
    String finalString="";

    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", address);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");
    Log.i("Check", "done pops");
    Session session = Session.getDefaultInstance(props, null);
    DataHandler handler=new DataHandler(new ByteArrayDataSource(finalString.getBytes(),"text/plain" ));
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setDataHandler(handler);
    Log.i("Check", "done sessions");

    multiPart=new MimeMultipart();

    InternetAddress toAddress;
    toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Log.i("Check", "added recipient");
    message.setSubject("Send Auto-Mail");
    message.setContent(multiPart);
    message.setText("Demo For Sending Mail in Android Automatically");

    Log.i("check", "transport");
    Transport transport = session.getTransport("smtp");
    Log.i("check", "connecting");
    transport.connect(host,address , pass);
    Log.i("check", "wana send");
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();

    Log.i("check", "sent");

}

}

Harshal Kalavadiya
  • 2,412
  • 4
  • 38
  • 71
0
connect to SMTP host: smtp.gmail.com, port: 465;
02-18 16:16:05.242: W/System.err(3242):   nested exception is:
02-18 16:16:05.242: W/System.err(3242):     javax.net.ssl.SSLHandshakeException: 
    java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

I believe you need to use Google Internet Authority G2, and build a chain back to the root.

If needed, provide a custom X509TrustManager and perform the chain building in checkServerTrusted. See, for example, Nikolay Elenkov's Using a Custom Certificate Trust Store on Android or Overriding the SSL Trust Manager in Android.

Community
  • 1
  • 1
jww
  • 97,681
  • 90
  • 411
  • 885
0

Here is my working code...

https://www.dropbox.com/s/cwz7qiw7q3qbx7b/Emailing.zip

Please use your valid email id for sender mail id and correct password.

GMailSender sender = new GMailSender("pankaj.sharma101987@gmail.com","******");
        sender.sendMail("Hii",   
                "Pankaj Test Mail",   
                "pankaj.sharma101987@gmail.com",   
                "receiver@gmail.com");

Here in code.then run the code.hope it works for you.

PankajSharma
  • 1,529
  • 14
  • 27