Android: Read Gmail Message Body From a Service with Gmail api

后端 未结 1 1220
猫巷女王i
猫巷女王i 2021-01-29 10:28

What I want that, from a service, I want to read the gmail message body when a gmail notification has arrived. When The Gmail Notification has arrived an alarm will occure and

相关标签:
1条回答
  • 2021-01-29 11:19

    Update: Extended version if anyone needs (Medium): https://shorturl.at/zKQR7


    First you need to make sure you are authenticated using Google. You can do that with Firebase Auth (before use, you will have to look how it's configured, there is good documentation available) :

                val providers = arrayListOf(
                    AuthUI.IdpConfig.GoogleBuilder().build()
                )
    
                startActivityForResult(
                    AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setAvailableProviders(providers)
                        .build(),
                    RQ_FIREBASE_AUTH
                )
    

    Once authenticated, you can use FirebaseAuth.getInstance().currentUser.

    Next step would be to setup Gmail service:

                val credential = GoogleAccountCredential.usingOAuth2(
                    applicationContext, listOf(GmailScopes.GMAIL_LABELS, GmailScopes.GMAIL_READONLY)
                )
                    .setBackOff(ExponentialBackOff())
                    .setSelectedAccountName(FirebaseAuth.getInstance().currentUser?.email)
    
                val service = Gmail.Builder(
                    NetHttpTransport(), AndroidJsonFactory.getDefaultInstance(), credential
                )
                    .setApplicationName("YourAppName")
                    .build()
    

    Please note the above is not production ready stuff of course.

    Finally, here is reading part:

    val messageRead = service.users().messages()?.get(FirebaseAuth.getInstance().currentUser?.email, message?.id)?.setFormat("raw")?.execute()
    

    So you can get a glimps into body of your message like this messageRead?.snippet

    There are two not obvious things to note though:

    1. You must expect and handle UserRecoverableAuthIOException exception. This is the point when user has to explicitly grant your app to do certain stuff with messages

    2. All these execute calls not be handle don main thread.

    Hope it helps! (sorry don't have time to write detailed how-to).

    0 讨论(0)
提交回复
热议问题