接入教程
1. 前往Google Cloud Console创建项目并启用Gmail API。
2. 配置OAuth 2.0凭据以获取访问权限。
3. 安装客户端库,如Google API Python客户端。
4. 使用授权令牌初始化API客户端。
5. 调用API方法,如列出邮件或发送新邮件。
6. 处理响应数据并集成到您的应用中。
使用Python读取收件箱邮件列表
import requests
url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages'
headers = {
'Authorization': 'Bearer YOUR_API_KEY'
}
params = {
'labelIds': 'INBOX',
'maxResults': 10
}
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
messages = response.json()
print(f'Found {len(messages.get('messages', []))} messages')
else:
print(f'Error: {response.status_code}')
print(response.text)
使用PHP发送一封简单邮件
<?php
$url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages/send';
$apiKey = 'YOUR_API_KEY';
$emailData = [
'raw' => base64_encode("To: recipient@example.com\r\nSubject: Test Email\r\n\r\nThis is the body of the email.")
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($emailData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
echo 'Email sent successfully.';
} else {
echo 'Failed to send email. HTTP Code: ' . $httpCode;
echo 'Response: ' . $response;
}
?>
使用JavaScript获取邮件标签列表
const url = 'https://gmail.googleapis.com/gmail/v1/users/me/labels';
const apiKey = 'YOUR_API_KEY';
async function fetchLabels() {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
console.log('Available labels:', data.labels);
} else {
console.error('Failed to fetch labels:', response.status);
}
} catch (error) {
console.error('Error fetching labels:', error);
}
}
fetchLabels();
常见问题
如何获取Gmail API的访问凭证?
您需要在Google Cloud Console中创建一个项目,启用Gmail API,并配置OAuth 2.0凭据。获取到客户端ID和密钥后,通过标准的OAuth流程获取访问令牌(Access Token),该令牌将作为YOUR_API_KEY用于API请求的Authorization头。
Gmail API有哪些主要的速率限制?
Gmail API对每个项目有每日配额限制(默认约100万次请求/天),并且对每用户每秒的请求数(QPS)也有限制。具体的限制数值取决于您的项目配置和使用情况,建议在Google Cloud Console的API配额页面查看和调整。
API请求中如何使用YOUR_API_KEY?
在向Gmail API发起请求时,您需要在HTTP请求的Authorization头中携带访问令牌。格式为:'Authorization: Bearer YOUR_API_KEY'。请确保使用有效的OAuth 2.0访问令牌,并且该令牌具有请求所需的作用域(scopes)。
Aitishiku.com