【问题标题】:Android: Read Gmail Message Body From a Service with Gmail apiAndroid:使用 Gmail api 从服务中读取 Gmail 邮件正文
【发布时间】:2020-06-21 05:56:21
【问题描述】:

我想要什么,从服务中,我想在 gmail 通知到达时阅读 gmail 消息正文。当 Gmail 通知到达时,会发生警报,​​我会在 alarmReceiver 中获得完整的正文。

我在这里获得了 android 快速入门 gsuits api:https://developers.google.com/gsuite/guides/android。但这里只描述了 Android Sdk 和 Dependencies。我没有找到捕获 gmail 正文的整个过程。

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 正文的逐步整个过程是什么?

【问题讨论】:

    标签: android gmail-api android-alarms incoming-mail


    【解决方案1】:

    更新:如果有人需要扩展版(中):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 调用都不是主线程的句柄。

    希望对您有所帮助! (抱歉没有时间写详细的操作方法)。

    【讨论】:

    • 请详细说明如何在java中使用完整的程序
    猜你喜欢
    • 2016-12-12
    • 1970-01-01
    • 2016-07-07
    • 2018-06-22
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 2018-05-18
    相关资源
    最近更新 更多