-3

I'm trying to send the mail on button click directly without using this application. Actually i copy this Code from Vinayak Bevinakatti. i follow his code but didnt work, i think i have a problem from SDK VERSION.

Build.app

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.coorsdev.sendsms"
    minSdkVersion 14
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

3

Send Mail Via JavaX Mail API

//-----------SEND MAIL ASYNC Task-------------\\
    public class SendMail extends AsyncTask<Void, Void, Void> {

        //Declaring Variables
        private Context context;
        private Session session;

        //Information to send email
        private String email;
        private String subject;
        private String message;

        //ProgressDialog to show while sending email
//        private ProgressDialog progressDialog;
        private ACProgressFlower progressDialog;

        //Class Constructor
        public SendMail(Context context, String email, String subject, String message) {
            //Initializing variables
            this.context = context;
            this.email = email;
            this.subject = subject;
            this.message = message;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //Showing progress dialog while sending email
//            progressDialog = ProgressDialog.show(context, "Sending message", "Please wait...", false, false);

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            //Dismissing the progress dialog
            //progressDialog.dismiss();
            //Showing a success message
            Toast.makeText(context, "Poll emailed", Toast.LENGTH_LONG).show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            //Creating properties
            Properties props = new Properties();

            //Configuring properties for gmail
            //If you are not using gmail you may need to change the values
            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");
            //Creating a new session
            session = Session.getDefaultInstance(props,
                    new javax.mail.Authenticator() {
                        //Authenticating the password
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(StaticValues.EMAIL, StaticValues.PASSWORD);
                        }
                    });

            try {
                //Creating MimeMessage object
                MimeMessage mm = new MimeMessage(session);

                //Setting sender address
                mm.setFrom(new InternetAddress(StaticValues.EMAIL));
                //Adding receiver
                mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
                //Adding subject
                mm.setSubject(subject);
                //Adding message
                mm.setText(message);

                //Sending email
                Transport.send(mm);

            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

Call this method like this:

//------------------Send Mail using JavaX Mail API----------------------\\
        SendMail sm = new SendMail(this, email, subject, message);
        sm.execute();
//-----------------------------------------------------------------------\\

Gradle Dependencies:

// JavaX Mail \\
compile 'com.sun.mail:android-mail:1.5.5'
compile 'com.sun.mail:android-activation:1.5.5'
//-------------\\

Project Level Gradle

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url "https://s3.amazonaws.com/repo.commonsware.com" }
        maven { url "https://maven.java.net/content/groups/public/" }
    }
}
Rahul Singh Chandrabhan
  • 2,531
  • 5
  • 22
  • 33
2

I suggest this pretty cool library. It is very simple heres how to do it just incase the link change, compile this to your project

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

//Project gradle
repositories {
    // ...
    maven { url "https://jitpack.io" }
}

//Module gradle
compile 'com.github.yesidlazaro:GmailBackground:1.2.0'

Then to use you just have to make an instance on your OnClick

BackgroundMail.newBuilder(this)
            .withUsername("username@gmail.com")
            .withPassword("password12345")
            .withMailto("toemail@gmail.com")
            .withType(BackgroundMail.TYPE_PLAIN)
            .withSubject("this is the subject")
            .withBody("this is the body")
            .withOnSuccessCallback(new BackgroundMail.OnSuccessCallback() {
                @Override
                public void onSuccess() {
                    //do some magic
                }
            })
            .withOnFailCallback(new BackgroundMail.OnFailCallback() {
                @Override
                public void onFail() {
                    //do some magic
                }
            })
            .send();

Note: You can send it in background by using

.withProcessVisibility(false)

Hope this helps.

Android_K.Doe
  • 753
  • 1
  • 4
  • 11
  • Great Answer. But is there any way to encrypt/safely store the password so that if any one decompiles the app also he is not able to access the password? – Rajesh K Jul 27 '18 at 11:10
  • @RajeshK use your personal dummy email in that section. Not email from user. You don't ask users for credential. – Android_K.Doe Jul 30 '18 at 01:28
  • I am intending to use my email only but for that is there an safe place to store the credential so that even someone reverse engineers the app he is not able to see the email with its password as I might be misused later. – Rajesh K Jul 31 '18 at 08:05
  • Can I send email to multiple users with this library? – Sumit Shukla Oct 06 '18 at 02:45
  • 1
    @SumitShukla yes by specifying `withMailto` with emails and comma separator – Android_K.Doe Oct 09 '18 at 06:37
  • man you saved my day. this is by far the best solution for sending emails via smtp – Akash Chaudhary Jan 15 '20 at 15:53