OAuth邮箱授权服务的完整设置和使用指南
最后更新:2025年7月28日
几分钟内快速开始使用OAuth邮箱授权服务
git clone https://github.com/hst-Sunday/mail-auth.git
cd mail-auth
npm install
# 或
yarn install
在项目根目录创建 `.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)
npm run dev
# 应用将运行在 http://localhost:3001
学习如何将OAuth邮箱授权服务集成到您的应用程序中
获取OAuth2授权URL
/api/auth/gmail-oauth
用户在Google授权页面上授予权限
处理Google返回的授权码
/api/auth/gmail-oauth/callback
用授权码交换访问令牌和刷新令牌
向Gmail API端点发出已认证的请求
/api/auth/gmail-oauth
获取OAuth2授权URL
/api/auth/gmail-oauth/callback
处理带授权码的OAuth2回调
/api/auth/refresh-token
刷新过期的访问令牌
/api/gmail/inbox
获取收件箱邮件
/api/gmail/sent
获取已发送邮件
/api/gmail/send
发送邮件消息
/api/gmail/search
使用查询搜索邮件
/api/gmail/message/[id]
通过ID获取特定邮件
/api/gmail/attachment/[messageId]/[attachmentId]
下载邮件附件
实用示例助您快速上手
// 获取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);
}
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;
}
}
常见问题及其解决方案
重要的安全注意事项