繁体   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