文档

OAuth邮箱授权服务的完整设置和使用指南

最后更新:2025年7月28日

📦 项目安装

几分钟内快速开始使用OAuth邮箱授权服务

系统要求
  • Node.js 18.0 或更高版本
  • npm 或 yarn 包管理器
  • Git 版本控制工具
1
1. 克隆项目
将项目克隆到本地计算机
git clone https://github.com/hst-Sunday/mail-auth.git
cd mail-auth
2
2. 安装依赖
安装所有必需的包
npm install
# 或
yarn install
3
3. 环境配置
设置环境变量

在项目根目录创建 `.env.local` 文件,包含以下变量:

.env.local
# .env.local
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_REDIRECT_URI=http://localhost:3001/api/auth/gmail-oauth/callback
NEXT_PUBLIC_SUCCESS_REDIRECT_HOST=http://localhost:3000
NEXT_PUBLIC_ACCEPT_DATA_URL=/api/accept-auth-info

环境变量

GOOGLE_CLIENT_ID

来自Google Cloud Console的OAuth2客户端ID

GOOGLE_CLIENT_SECRET

Google OAuth2客户端密钥

GOOGLE_REDIRECT_URI

OAuth2重定向URI(默认:http://localhost:3001/api/auth/gmail-oauth/callback)

NEXT_PUBLIC_SUCCESS_REDIRECT_HOST

成功授权后重定向的主机(默认:http://localhost:3000)

NEXT_PUBLIC_ACCEPT_DATA_URL

接受access_token的API端点(默认:/api/accept-auth-info)

4
4. 启动开发服务器
在开发模式下启动应用程序
npm run dev
# 应用将运行在 http://localhost:3001
Google Cloud Console设置
按照以下步骤在Google Cloud Console中配置OAuth2:
  1. 1访问Google Cloud Console (https://console.cloud.google.com/)
  2. 2创建新项目或选择现有项目
  3. 3为项目启用Gmail API
  4. 4转到凭据 → 创建凭据 → OAuth 2.0客户端ID
  5. 5将应用程序类型设置为'Web应用程序'
  6. 6添加授权重定向URI
  7. 7复制您的客户端ID和客户端密钥

🔧 使用指南

学习如何将OAuth邮箱授权服务集成到您的应用程序中

OAuth2授权流程
完整的OAuth2流程包含以下步骤:
1

初始化授权

获取OAuth2授权URL

/api/auth/gmail-oauth
2

用户授权

用户在Google授权页面上授予权限

3

处理回调

处理Google返回的授权码

/api/auth/gmail-oauth/callback
4

交换令牌

用授权码交换访问令牌和刷新令牌

5

使用Gmail API

向Gmail API端点发出已认证的请求

API端点

身份验证
GET
/api/auth/gmail-oauth
?locale=zh(可选)

获取OAuth2授权URL

GET
/api/auth/gmail-oauth/callback

处理带授权码的OAuth2回调

POST
/api/auth/refresh-token

刷新过期的访问令牌

Gmail操作
GET
/api/gmail/inbox

获取收件箱邮件

GET
/api/gmail/sent

获取已发送邮件

POST
/api/gmail/send

发送邮件消息

GET
/api/gmail/search

使用查询搜索邮件

GET
/api/gmail/message/[id]

通过ID获取特定邮件

GET
/api/gmail/attachment/[messageId]/[attachmentId]

下载邮件附件

💡 代码示例

实用示例助您快速上手

基础OAuth2流程
简单的OAuth2授权示例
基础OAuth流程
// 获取OAuth授权URL
const response = await fetch('/api/auth/gmail-oauth?locale=en');
const data = await response.json();

if (data.authUrl) {
  // 重定向到Google授权页面
  window.location.href = data.authUrl;
} else {
  console.error('获取授权URL失败:', data.error);
}
使用GmailService类
通过服务类进行高级Gmail操作
使用GmailService类
import { GmailService } from '@/lib/gmail-service';

// 创建Gmail服务实例
const gmailService = new GmailService(accessToken);

// 获取收件箱邮件
const inbox = await gmailService.getInbox(10);
console.log('收件箱邮件:', inbox);

// 搜索邮件
const searchResults = await gmailService.searchEmails('from:example@gmail.com', 5);
console.log('搜索结果:', searchResults);

// 获取特定邮件
const message = await gmailService.getMessage(messageId);
console.log('邮件详情:', message);
发送邮件
发送带附件的邮件
发送邮件示例
// 发送邮件
const emailParams = {
  to: 'recipient@example.com',
  subject: '测试邮件',
  body: '这是一封测试邮件的内容。',
  cc: 'cc@example.com', // 可选
  attachments: [ // 可选
    {
      filename: 'document.pdf',
      mimeType: 'application/pdf',
      content: base64EncodedContent
    }
  ]
};

const result = await gmailService.sendEmail(emailParams);
console.log('邮件发送成功:', result);
令牌刷新
自动刷新过期的令牌
令牌刷新示例
// 刷新访问令牌
async function refreshAccessToken(refreshToken) {
  try {
    const response = await fetch('/api/auth/refresh-token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ refresh_token: refreshToken })
    });

    const data = await response.json();
    
    if (data.access_token) {
      // 使用新的访问令牌
      console.log('令牌刷新成功:', data.access_token);
      return data;
    } else {
      throw new Error(data.error || '刷新令牌失败');
    }
  } catch (error) {
    console.error('刷新令牌错误:', error);
    throw error;
  }
}

🛠️ 故障排除

常见问题及其解决方案

常见问题

OAuth回调失败,显示"无效的重定向URI"
确保Google Cloud Console中的重定向URI与.env文件中的GOOGLE_REDIRECT_URI完全匹配
访问令牌很快过期
使用刷新令牌获取新的访问令牌。在应用程序中实现自动令牌刷新
Gmail API配额超限
在Google Cloud Console中检查API使用情况。考虑实施速率限制和缓存策略
调用API时出现CORS错误
所有API端点都包含CORS标头。确保您从允许的来源调用
调试技巧
  • 检查浏览器控制台的错误消息
  • 验证环境变量是否正确加载
  • 使用Google Cloud Console API Explorer测试Gmail API调用
  • 在应用程序中启用调试日志
  • 检查网络选项卡中失败的API请求

🔒 安全最佳实践

重要的安全注意事项

🔒 安全最佳实践
  • 永远不要在前端代码中暴露您的客户端密钥
  • 在生产环境中使用HTTPS
  • 实施适当的令牌存储和加密
  • 定期轮换您的OAuth2凭据
  • 验证和清理所有用户输入
  • 监控API使用情况以识别可疑活动