Mail Server Solution(4)gmail API Demo

使用Java实现Gmail API的快速入门教程
Mail Server Solution(4)gmail API Demo

1. API Introduction
It should be working. Here is some API I may need later.
gmail.users.messages.list
userId-email address
labelIds-INBOX
q-job.craigslist.org
gmail.users.messages.get
userId-email address
id-message id I get in the previous API
response-playload, sizeEstimate
gmail.users.messages.attachments.get
userId-email address
messageId-message id I get in the first API
id-attachment file id I get in the previous API
fields-data and size

2. Admin Console Configuration
Visit the google developer’s console
https://console.developers.google.com

Go to APIs&Auth —> Credentials —> I select the installed application for demo

After that I download a JSON file which will have some keys there with name similar to xxxx.json
Actually, I should use this one later
https://developers.google.com/identity/protocols/OAuth2?hl=en_US#serviceaccount

3. Set up Sample with gradle and JAVA
Install Gradle Again with Latest Version
That is amazing, the version is gradle 2.5 now. I was using 1.1 or 1.2 before.
http://sillycat.iteye.com/blog/1074642
http://sillycat.iteye.com/blog/2090147

Place it in the right place and add to the path.

mkdir and prepare the working directory
> pwd
/Users/carl/work/gradle/gmailapi
> gradle init --type basic

Generate the source directory
> mkdir -p src/main/java src/main/resources
Copy and prepare the JSON key file under src/main/resources
Copy and Place the JAVA data there. It is working pretty well.

build.gradle
apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'eclipse'

mainClassName = 'com.sillycat.gmailapi.GmailQuickstart'
sourceCompatibility = 1.7
targetCompatibility = 1.7
version = '1.0'

repositories {
jcenter()
mavenCentral()
}

dependencies {
compile 'com.google.api-client:google-api-client:1.20.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.20.0'
compile 'com.google.apis:google-api-services-gmail:v1-rev29-1.20.0'
compile 'org.slf4j:slf4j-api:1.7.12'
testCompile 'junit:junit:4.12'
}

Here is the codes
package com.sillycat.gmailapi;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;

import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.*;
import com.google.api.services.gmail.Gmail;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class GmailQuickstart {

/** Application name. */
private static final String APPLICATION_NAME = "Gmail API Java Quickstart";

/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"),
".credentials/gmail-api-quickstart");

/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;

/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory
.getDefaultInstance();

/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;

/** Global instance of the scopes required by this quickstart. */
private static final List<String> SCOPES = Arrays
.asList(GmailScopes.GMAIL_LABELS);

static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}

/**
* Creates an authorized Credential object.
*
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in = GmailQuickstart.class
.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
JSON_FACTORY, new InputStreamReader(in));

// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline").build();
Credential credential = new AuthorizationCodeInstalledApp(flow,
new LocalServerReceiver()).authorize("user");
System.out.println("Credentials saved to "
+ DATA_STORE_DIR.getAbsolutePath());
return credential;
}

/**
* Build and return an authorized Gmail client service.
*
* @return an authorized Gmail client service
* @throws IOException
*/
public static Gmail getGmailService() throws IOException {
Credential credential = authorize();
return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}

public static void main(String[] args) throws IOException {
// Build a new authorized API client service.
Gmail service = getGmailService();

// Print the labels in the user's account.
String user = "me";
ListLabelsResponse listResponse = service.users().labels().list(user)
.execute();
List<Label> labels = listResponse.getLabels();
if (labels.size() == 0) {
System.out.println("No labels found.");
} else {
System.out.println("Labels:");
for (Label label : labels) {
System.out.printf("- %s\n", label.getName());
}
}
}

}

Generate the eclipse structure and import to eclipse
> gradle eclipse

Run the application
> gradle run --stacktrace

References:
https://developers.google.com/gmail/api/
https://developers.google.com/gmail/api/quickstart/java
https://developers.google.com/api-client-library/java/apis/gmail/v1
https://developers.google.com/apis-explorer/#p/gmail/v1/
### Docker Compose 停止时出现 500 Internal Server Error 和退出状态码为 1 的原因分析 当使用 `docker-compose` 运行多个微服务并尝试通过 `docker-compose stop` 或其他命令停止容器时,如果遇到 **500 Internal Server Error** 并伴随退出状态码为 1,则可能是由以下几个方面引起: #### 1. API 路由配置错误 如果某个微服务依赖于另一个微服务的 API 接口,在关闭过程中可能会触发未处理的异常。例如,某些微服务可能在关闭前仍然试图调用已停止的服务中的 API 路径[^2]。这种情况下,建议检查以下几点: - 确认所有微服务之间的通信路径是否正确设置。 - 验证是否存在硬编码的 IP 地址或端口号,这些可能导致连接失败。 #### 2. 版本兼容性问题 不同版本的 `docker-compose` 文件格式可能存在不兼容的情况。如果使用的 `compose` 文件版本较高而本地安装的工具链较低,或者反之亦然,则可能出现意外行为[^3]。解决方法如下: - 使用匹配当前环境支持的 `version` 字段定义 compose 文件。例如,对于较新的 Docker Engine 及其插件架构推荐采用 `v3.x` 格式;而对于更老的基础设施则应考虑回退至 `v2.x`。 ```yaml version: '3.8' services: web: image: my_web_service_image ports: - "80:80" ``` #### 3. 容器健康检查机制失效 部分框架会在应用正常终止之前执行清理操作(如释放资源)。然而,若此过程未能顺利完成——比如由于数据库锁定或其他外部因素干扰——那么整个流程就有可能中断从而引发 HTTP 错误响应[^4]。针对这种情况可采取措施包括但不限于调整超时参数、优化事务管理逻辑等手段来增强系统的鲁棒性。 #### 4. 日志记录不足影响排查效率 为了更好地定位具体哪个环节出了差错,应该启用详尽的日志输出模式以便收集更多上下文信息用于后续诊断工作[^5]。可以通过修改 docker-compose.yml 中的相关选项实现这一目标: ```yaml logging: driver: "json-file" options: max-size: "10m" max-file: "3" ``` 以上策略能够帮助减少因缺乏足够的调试数据而导致误解的可能性。 --- ### 总结 综上所述,要彻底解决问题需从四个方面入手:一是审查各组件间交互关系确保无遗漏之处;二是核实所选用的技术栈规格一致性避免潜在冲突发生;三是强化程序内部防护能力防止中途崩溃现象再现;四是完善监控体系积累必要证据辅助决策制定过程。只有这样才能够有效应对诸如 “stop command returns with exit code 1 and throws a 500 internal server error” 类似的挑战。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值