簡體   English   中英

Android:使用 Gmail api 從服務讀取 Gmail 郵件正文

[英]Android: Read Gmail Message Body From a Service with Gmail api

我想要的是,從服務中,我想在 gmail 通知到達時閱讀 gmail 郵件正文。 當 Gmail 通知到達時,會發生警報,​​我會在 alarmReceiver 中獲取全文。

我在這里 gsuits api 獲得了 android 快速入門: https : //developers.google.com/gsuite/guides/android 但是只描述了 Android Sdk 和依賴項。 我沒有找到捕獲 gmail body 的整個過程。

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.google.android.gms:play-services-auth:15.0.1'
compile 'pub.devrel:easypermissions:0.3.0'
compile('com.google.api-client:google-api-client-android:1.23.0') {
    exclude group: 'org.apache.httpcomponents'
}
compile('com.google.apis:google-api-services-<API>-<VERSION>') {
    exclude group: 'org.apache.httpcomponents'
}}

在那之后,我可以在我的android應用程序中檢索/獲取gmail正文的分步整個過程是什么?

更新:如果有人需要擴展版本(中): https : //shorturl.at/zKQR7


首先,您需要確保使用 Google 進行身份驗證。 您可以使用 Firebase Auth(在使用之前,您必須查看它的配置方式,有很好的文檔可用)來做到這一點:

            val providers = arrayListOf(
                AuthUI.IdpConfig.GoogleBuilder().build()
            )

            startActivityForResult(
                AuthUI.getInstance()
                    .createSignInIntentBuilder()
                    .setAvailableProviders(providers)
                    .build(),
                RQ_FIREBASE_AUTH
            )

通過身份驗證后,您可以使用FirebaseAuth.getInstance().currentUser

下一步是設置 Gmail 服務:

            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()

請注意,以上當然不是生產就緒的東西。

最后,這里是閱讀部分:

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

因此,您可以像這樣messageRead?.snippet一瞥消息正文

不過,有兩件不明顯的事情需要注意:

  1. 您必須預期並處理UserRecoverableAuthIOException異常。 這就是用戶必須明確授權您的應用對消息執行某些操作的關鍵點

  2. 所有這些execute調用都不會在主線程中處理。

希望能幫助到你! (抱歉沒有時間寫詳細的操作方法)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM