Skip to content Skip to sidebar Skip to footer

Use Gmail Api For Send Mail Via Android App

I know there are a lot of toturials, questions etc and I was working on it at the past weeks but couldn't figure it out. I am developing an Android app that I want to send an email

Solution 1:

I will try to answer your multiple question

  1. No, you don't need a G Suite account to use the Gmail API, you can do it with a normal gmail account.

  2. The guide that you linked is fine, just think that inside an app or in a console, the API works over HTTPs request with a REST architecture, therefore you can use the API in any platform that support HTTP requests.

  3. This last bit will depend highly on the architecture you are using, and take into consideration that I'm not an Android expert. But the "difficult" part will be to get the authorization from the user, but I believe you can do it normally with Java.

Useful links

Solution 2:

Initial steps :

  1. You need to sign in the web browser with your google account.

    you will get redirect error if you do not error 400 etc..

  2. Add app to google cloud platform, add sha-1 key, for all signatures you will be using

  3. Create a web app with pesky redirected URL !! enter image description here

The final console will look like this:enter image description here

  1. Download the web app credential.json. put it in new folder app/resources enter image description here

    class GmailQuickstart {

    privatestaticfinalStringAPPLICATION_NAME="com.emable.getlabels" ; 
    privatestaticfinalJsonFactoryJSON_FACTORY= JacksonFactory.getDefaultInstance();
    privatestaticfinalStringTOKENS_DIRECTORY_PATH="tokens";
    
    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */privatestaticfinal List<String> SCOPES = Collections.singletonList( GmailScopes.GMAIL_LABELS ) ;
    privatestaticfinalStringCREDENTIALS_FILE_PATH="/credentials.json";
    
    
    
    publicstatic Message sendMessage(Gmail service,
                                      String userId,
                                      MimeMessage emailContent)throws MessagingException, IOException {
        Messagemessage= createMessageWithEmail(emailContent);
        message = service.users().messages().send(userId, message).execute();
    
        System.out.println("Message id: " + message.getId());
        System.out.println(message.toPrettyString());
        return message;
    }
    
     publicstatic Message createMessageWithEmail(MimeMessage emailContent)throws MessagingException, IOException {
         ByteArrayOutputStreambuffer=newByteArrayOutputStream();
         emailContent.writeTo(buffer);
         byte[] bytes = buffer.toByteArray();
         StringencodedEmail= Base64.encodeBase64URLSafeString(bytes);
         Messagemessage=newMessage();
         message.setRaw(encodedEmail);
         return message;
     }
    
    privatestaticLocalServerReceiverlocalServerReceiver=null;
    privatestaticAuthorizationCodeInstalledApplocalAuthorizationCodeInstalledApp=null;
    
    privatestatic Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT,Context context, String personId)throws IOException {
        // Load client secrets.InputStreamin= GmailQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            thrownewFileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
    
        GoogleClientSecretsclientSecrets= GoogleClientSecrets.load(JSON_FACTORY, newInputStreamReader(in));
    
        // Build flow and trigger user authorization request.GoogleAuthorizationCodeFlowflow=newGoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(newFileDataStoreFactory(  context.getFilesDir() )) // new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("online")
                .setApprovalPrompt("force")
                .build();
         if (localServerReceiver == null) {
             localServerReceiver = newLocalServerReceiver.Builder().setPort(8888).build();
         }else{
             localServerReceiver.stop();
             localServerReceiver = newLocalServerReceiver.Builder().setPort(8888).build();
         }
    
        AuthorizationCodeInstalledApplAuthorizationCodeInstalledApp=newAuthorizationCodeInstalledApp(flow, localServerReceiver) {
                protectedvoidonAuthorization(AuthorizationCodeRequestUrl authorizationUrl)throws IOException {
                    Stringurl= (authorizationUrl.build());
                    IntentbrowserIntent=newIntent(Intent.ACTION_VIEW, Uri.parse(url));
                    (context).startActivity(browserIntent);
                }
            };
    
        return lAuthorizationCodeInstalledApp.authorize("user");
    }
    
    publicstaticvoidstart(Context c,String personId, TextView tview)throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.finalNetHttpTransportHTTP_TRANSPORT=newcom.google.api.client.http.javanet.NetHttpTransport();
    
        Gmailservice=newGmail.Builder(HTTP_TRANSPORT, JSON_FACTORY,  getCredentials(HTTP_TRANSPORT, c, personId))
                .setApplicationName(APPLICATION_NAME)
                .build();
        newHandler(Looper.getMainLooper()).post(newRunnable() {
            @Overridepublicvoidrun() {
                Toasttoast= Toast.makeText(c,"Gmail service ok", Toast.LENGTH_SHORT);
                toast.show();
            }
        });
        Log.i("TAG", "BLA");
        // Print the labels in the user's account.Stringuserid="me";
        ListLabelsResponselistResponse= service.users().labels().list(userid).execute();
        List<Label> labels = listResponse.getLabels();
        //service.if (labels.isEmpty()) {
            Log.i("TAG","  No Labels ");
    
        } else {
    
            for (Label label : labels) {
                newHandler(Looper.getMainLooper()).post(newRunnable() {
                    @Overridepublicvoidrun() {
                        Toasttoast= Toast.makeText(c, label.toString(), Toast.LENGTH_SHORT);
                        toast.show();
                    }
                });
            }
        }
    }
    

This function can be called by a button in the Avtivity for example.

publicvoid SendEmailTest(Context context){

       AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
           @Override
           protectedString doInBackground(Void... params) {
               try {
                   try {
                      // ignore personId, tview your dont  really need them
                       GmailQuickstart.start(context, personId, tview);
                   } catch (IOException e) {
                       e.printStackTrace();
                   } catch (GeneralSecurityException e) {
                       e.printStackTrace();
                   }
               } catch (Exception e) {
                   e.printStackTrace();
               }
               return"";

           };

       };
       asyncTask.execute();





   }

Add user permission:

<uses-permissionandroid:name="android.permission.GET_ACCOUNTS" /><uses-permissionandroid:name="android.permission.INTERNET"/><uses-permissionandroid:name="android.permission.READ_SMS"/><uses-permissionandroid:name="android.permission.RECEIVE_SMS" /><uses-permissionandroid:name="android.permission.SMS_RECEIVED" /><uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permissionandroid:name="com.android.vending.BILLING" />

Gradle:

plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"
    repositories {
        google()
    }
    defaultConfig {
        applicationId "      bla bla bla bla bla your app id here"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 2
        versionName "1.0"
        multiDexEnabled true


        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            debuggable false
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildFeatures {
        viewBinding true
    }
    lintOptions {
        checkReleaseBuilds false
    }

}




dependencies {

    implementation 'androidx.multidex:multidex:2.0.1'defbilling_version="4.0.0"

    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'com.google.android.gms:play-services-auth:19.2.0'
    implementation 'androidx.navigation:navigation-fragment:2.3.0'
    implementation 'androidx.navigation:navigation-ui:2.3.0'
    debugImplementation files('app/libs')
    debugImplementation fileTree(dir: 'libs', include: ['*.aar', '*.jar'], exclude: [])
    implementation fileTree(dir: 'libs', include: ['*.aar', '*.jar'], exclude: [])
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation "com.android.billingclient:billing:$billing_version"

    implementation 'com.google.api-client:google-api-client:1.23.0'
    implementation 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
    implementation 'com.google.apis:google-api-services-gmail:v1-rev83-1.23.0'




}

change the GmailScopes.GMAIL_LABELS to what ever GOD HELP US ALL

Post a Comment for "Use Gmail Api For Send Mail Via Android App"