Android应用调用Gmail API读取收件箱消息的后续步骤咨询
别慌!卡了3天确实闹心,我来把认证后读取Gmail收件箱的具体步骤给你掰碎了讲——其实核心就是用认证后的凭证构建Gmail服务实例,再调用对应的API接口:
一、先把依赖里的占位符补全
快速入门里的依赖有个占位符<API>-<VERSION>,你得换成Gmail API的具体信息。比如用最新稳定版的话,把那行改成:
compile('com.google.apis:google-api-services-gmail:v1-rev20240529-2.0.0') { exclude group: 'org.apache.httpcomponents' }
完整的dependencies配置大概是这样:
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-gmail:v1-rev20240529-2.0.0') { exclude group: 'org.apache.httpcomponents' } }
二、用认证后的凭证构建Gmail服务实例
快速入门里已经帮你搞定了OAuth2认证,拿到GoogleAccountCredential对象后,就可以创建Gmail服务实例了:
// 假设你已经通过快速入门的流程完成认证,拿到了credential对象 Gmail gmailService = new Gmail.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), credential) .setApplicationName("你的应用名称") // 填你在Google Cloud控制台设置的应用名称 .build();
三、调用API读取收件箱内容
接下来就是核心的API调用,分两步:先拿邮件列表,再拿单封邮件的完整内容。
3.1 获取收件箱的邮件列表
用users().messages().list()方法,参数"me"代表当前登录的用户,还可以用setQ()过滤收件箱邮件:
try { // 请求获取收件箱中最近10条邮件 ListMessagesResponse response = gmailService.users().messages().list("me") .setQ("in:inbox") // 过滤条件:只看收件箱里的邮件 .setMaxResults(10L) .execute(); List<Message> messages = response.getMessages(); if (messages != null && !messages.isEmpty()) { for (Message message : messages) { Log.d("GmailDemo", "邮件ID: " + message.getId() + " | 预览: " + message.getSnippet()); // 调用方法获取完整邮件内容 fetchFullMessageDetails(gmailService, message.getId()); } } else { Log.d("GmailDemo", "收件箱里暂时没有邮件~"); } } catch (IOException e) { Log.e("GmailDemo", "获取邮件列表失败", e); }
3.2 获取单封邮件的完整信息
写个工具方法,调用users().messages().get()获取邮件的主题、发件人、正文等细节:
private void fetchFullMessageDetails(Gmail gmailService, String messageId) throws IOException { // 请求完整格式的邮件内容 Message fullMessage = gmailService.users().messages().get("me", messageId) .setFormat("full") .execute(); // 提取邮件主题和发件人(从邮件头里找) String subject = ""; String sender = ""; List<MessagePartHeader> headers = fullMessage.getPayload().getHeaders(); for (MessagePartHeader header : headers) { if ("Subject".equalsIgnoreCase(header.getName())) { subject = header.getValue(); } else if ("From".equalsIgnoreCase(header.getName())) { sender = header.getValue(); } } // 提取邮件正文(处理纯文本和多部分邮件两种情况) String emailBody = ""; MessagePart payload = fullMessage.getPayload(); if (payload.getBody().getData() != null) { // 纯文本邮件直接解码 emailBody = new String(Base64.decodeBase64(payload.getBody().getData()), StandardCharsets.UTF_8); } else { // 多部分邮件,找纯文本部分 List<MessagePart> parts = payload.getParts(); for (MessagePart part : parts) { if ("text/plain".equals(part.getMimeType())) { emailBody = new String(Base64.decodeBase64(part.getBody().getData()), StandardCharsets.UTF_8); break; } } } // 打印结果,或者更新UI Log.d("GmailDemo", "主题: " + subject); Log.d("GmailDemo", "发件人: " + sender); Log.d("GmailDemo", "正文: " + emailBody); }
四、别忘了权限配置
要确保你在Google Cloud控制台开启了Gmail API,并且认证时请求了正确的权限范围。比如只读收件箱的话,用GMAIL_READONLY:
// 在创建GoogleAccountCredential的时候指定权限 GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2( getApplicationContext(), Arrays.asList(GmailScopes.GMAIL_READONLY)) .setBackOff(new ExponentialBackOff());
这样一步步走下来,就能成功读取Gmail收件箱的消息了!
内容的提问来源于stack exchange,提问作者Noor Hossain
相关产品推荐
相关产品推荐

